10

Say I have two vector<int>s:

vector<int> foo{1, 2, 3};
vector<int> bar{10, 20, 30};

Now I want to do a vector add on them such that the result would be:

11
22
33

Is there an STL algorithm that will handle this, or do I need to use a for loop:

for(auto i = 0; i < foo.size(); ++i){
    foo[i] += bar[i];
}

Bonus question, what if I wanted to do something more complicated than an add, say foo was a vector<string> and bar was still a vector<int>. I'm hoping that, if there is an STL algorithm I can use, it would also support lambdas?

Jonathan Mee
  • 35,107
  • 16
  • 95
  • 241
  • Templated operator overloading? – CinCout Mar 10 '15 at 11:06
  • @GregAnkit No, I am not trying to come up with my own operators, I just need an STL algorithm which will perform a function taking in the corresponding elements of two vectors and assigning the value back to one of them. – Jonathan Mee Mar 10 '15 at 11:27
  • @GargAnkit Incidentally there is a question about overloading `vector`'s operators though, if you're interested: http://stackoverflow.com/q/6366231/2642059 – Jonathan Mee Mar 10 '15 at 11:36

1 Answers1

20

What you want to do can be achieved using std::transform. In your case:

std::transform(foo.begin(), foo.end(), bar.begin(), foo.begin(), std::plus<int>());

std::transform does support lambdas as well so you can do more complicated operations between vector elements.

Jonathan Mee
  • 35,107
  • 16
  • 95
  • 241
mkaes
  • 12,760
  • 9
  • 50
  • 67
  • 1
    I feel kinda silly now, I thought `std::transform` only had a unary operation format. – Jonathan Mee Mar 10 '15 at 11:33
  • I have an amateurish question: What is happening deep inside, is still a loop, am I right? – Pouya Mar 10 '15 at 13:14
  • 2
    @Pouya Probably, the standard does not specify how STL algorithms must be implemented by compilers, so in the future they might use multiple cores to implement this or who knows what. Which is one of the reasons it's better to use STL algorithms than your own loops. But for now, yeah it's probably just a loop. That's the suggested implementation of cplusplus.com anyway: http://www.cplusplus.com/reference/algorithm/transform/ – Jonathan Mee Mar 10 '15 at 13:35
  • 2
    For this actual case, there is a realistic chance of the vectorizer spotting the loop and replacing it with a vectorized version. Not that this would improve your N=3 case, but it would help for N=3000. – MSalters Mar 10 '15 at 15:37