Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 722
Jonathan Mee Avatar asked Mar 10 '15 10:03

Jonathan Mee


People also ask

How do you find the sum of a vector in STL?

Approach: Sum can be found with the help of accumulate() function provided in STL. Syntax: accumulate(first_index, last_index, initial value of sum);

How are vectors implemented in STL?

Vector is implemented as a dynamically allocated array. The memory for this array is allocated in the constructor. As more elements are inserted the array is dynamically increased in size. A constructor without parameter creates an array with a default size.

How do you add one vector to another?

To insert/append a vector's elements to another vector, we use vector::insert() function. Syntax: //inserting elements from other containers vector::insert(iterator position, iterator start_position, iterator end_position);

How do you find a vector in STL?

You can use the find function, found in the std namespace, ie std::find . You pass the std::find function the begin and end iterator from the vector you want to search, along with the element you're looking for and compare the resulting iterator to the end of the vector to see if they match or not.


1 Answers

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.

like image 159
mkaes Avatar answered Oct 08 '22 22:10

mkaes