Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

STL way to add a constant value to a std::vector

Tags:

c++

stl

Is there an algorithm in the standard library that can add a value to each element of a std::vector? Something like

std::vector<double> myvec(5,0.); std::add_constant(myvec.begin(), myvec.end(), 1.); 

that adds the value 1.0 to each element?

If there isn't a nice (e.g. short, beautiful, easy to read) way to do this in STL, how about boost?

like image 923
Hans Avatar asked Dec 16 '10 13:12

Hans


People also ask

How do you add values to a vector in a set?

Get the vector to be converted. Create an empty set, to store the result. Iterate through the vector one by one, and insert each element into the set. Print the resultant set.

How do you modify a vector in C++?

C++ Vector Library - resize() FunctionThe C++ function std::vector::resize() changes the size of vector. If n is smaller than current size then extra elements are destroyed. If n is greater than current container size then new elements are inserted at the end of vector.

How do you add an element to an array in vector?

Insertion: Insertion in array of vectors is done using push_back() function. Above pseudo-code inserts element 35 at every index of vector <int> A[n]. Traversal: Traversal in an array of vectors is perform using iterators.


2 Answers

Even shorter using lambda functions, if you use C++0x:

std::for_each(myvec.begin(), myvec.end(), [](double& d) { d+=1.0;}); 
like image 133
Gene Bushuyev Avatar answered Sep 28 '22 02:09

Gene Bushuyev


Take a look at std::for_each and std::transform. The latter accepts three iterators (the begin and end of a sequence, and the start of the output sequence) and a function object. There are a couple of ways to write this. One way, using nothing but standard stuff, is:

transform(myvec.begin(), myvec.end(), myvec.begin(),           bind2nd(std::plus<double>(), 1.0));               

You can do it with for_each as well, but the default behavior of std::plus won't write the answer back to the original vector. In that case you have to write your own functor. Simple example follows:

struct AddVal {     double val;     AddVal(double v) : val(v);      void operator()(double &elem) const     {         elem += v;     } };  std::for_each(myvec.begin(), myvec.end(), AddVal(1.0)); 
like image 39
Michael Kristofik Avatar answered Sep 28 '22 03:09

Michael Kristofik