Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Element-wise tuple addition

Tags:

c++

tuples

I have some values held in a tuple, and I am looking to add another tuple to it element-wise. So I would like functionality like this:

std::tuple<int,int> a = {1,2}; std::tuple<int,int> b = {2,4};   std::tuple<int,int> c = a + b; // possible syntax 1 a += b; // possible syntax 2 a += {2,4}; // possible syntax 3 

Where the output tuple would have the value {3,6}

Was looking at CPP reference, but I couldn't find this functionality. It's possible that this and this question are relevant, however the answers are obfuscated by other complexities.

like image 443
Prunus Persica Avatar asked Jun 12 '18 10:06

Prunus Persica


People also ask

How do you add a tuple element wise?

To add two tuples element-wise:Use the zip function to get an iterable of tuples with the corresponding items. Use a list comprehension to iterate over the iterable. On each iteration, pass the tuple to the sum() function.

How do you sum two tuples in Python?

When it is required to add the tuples, the 'amp' and lambda functions can be used. The map function applies a given function/operation to every item in an iterable (such as list, tuple). It returns a list as the result.

Can you add 2 tuples together?

You can, however, concatenate 2 or more tuples to form a new tuple. This is because tuples cannot be modified.

Which method is used in tuple for adding element?

Using append() method A new element is added to the end of the list using the append() method.


1 Answers

You could also consider using std::valarray since it allows exactly the things that you seem to want.

#include <valarray>  int main() {     std::valarray<int> a{ 1, 2 }, b{ 2, 4 }, c;     c = a - b; // c is {-1,-2}     a += b; // a is {3,6}     a -= b; // a is {1,2} again     a += {2, 4}; // a is {3,6} again     return 0; } 
like image 91
Vishaal Shankar Avatar answered Oct 13 '22 14:10

Vishaal Shankar