Jonathan Mee
Jonathan Mee

Reputation: 38919

STL algorithm for Vector Add

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?

Upvotes: 10

Views: 1611

Answers (1)

mkaes
mkaes

Reputation: 14119

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.

Upvotes: 21

Related Questions