1. ## STL: element-wise addition of the contents of two containers

Aloha-

Is there an algorithm/function in the STL that will allow elementwise addition of two vectors/deques/etc.? In other words, given two vectors x and y, is there an operator that will return z such that

z.at( i ) == x.at( i ) + y.at( i ) ?

I have computed results using for loops and iterators, but am curious if there is functionality already built into the STL to do this (presumably) basic function.

Many thanks
Claus Hetzer 2. >but am curious if there is functionality already built into the STL
>to do this (presumably) basic function.
Basic yes. Generic, no. The STL containers must be able to hold just about anything, and addition isn't allowed on some data types, such as pointers. So adding a method to the containers to add all of the elements of two containers would be handling a special case, which goes against the concept of the STL. This is a trivial operation to perform anyway, so why not just code it by hand or use some of the STL function objects to handle your special case?

Just because something isn't already there and prewritten for you to use doesn't mean you can't mix and match what is there to get the functionality that you want.

-Prelude 3. Yeah, it's easy to code, but since I do a lot of numerical processing, I was hoping there was something precoded in the package that might be faster than what I can code by hand.

Thanks for the reply  4. An STL way might be something like -

Code:
```#include <iostream>
#include <vector>
#include <algorithm>
#include <functional>

using namespace std;

int main()
{
vector<int> a,b;
vector <int> c(3);
a.push_back(1);
a.push_back(2);
a.push_back(3);

b.push_back(3);
b.push_back(2);
b.push_back(1);

transform(a.begin(),a.end(),b.begin(),c.begin(),plus<int>());

copy(c.begin(),c.end(),ostream_iterator<int>(cout,"\n"));

return 0;
}```
I doubt there'll be much in the way of performance benefit, though. 5. You may want to consider using valarray if you're interested in an STL approach to numeric processing...

Code:
```#include <valarray>
#include <iostream>

double myArr[] = {1, 2, 3, 4, 5};

template <class T> void printVal (valarray <T> myVal);

int main (void) {
valarray <double> A (myArr, 5);
printVal (A);
valarray <double> B (A);
B+= 1;
printVal (B);

valarray <double> C (A + B);
printVal (C);

return 0;
}

template <class T> void printVal (valarray <T> myVal) {
for (int i = 0; i < myVal.size(); i++) {
cout << myVal[i] << ' ';
}
cout << '\n';
return;
}``` Popular pages Recent additions 