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?
Approach: Sum can be found with the help of accumulate() function provided in STL. Syntax: accumulate(first_index, last_index, initial value of sum);
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.
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);
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.
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.
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