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.
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.
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.
You can, however, concatenate 2 or more tuples to form a new tuple. This is because tuples cannot be modified.
Using append() method A new element is added to the end of the list using the append() method.
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; }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With