STL way to add a constant value to a std::vector
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?
Even shorter using lambda functions, if you use C++0x:
std::for_each(myvec.begin(), myvec.end(), [](double& d) { d+=1.0;});
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));
The shortest way in plain C++0X is :
for(double& d : myvec)
d += 1.0;
and with boost :
for_each(myvec, _1 += 1.0); // boost.range + boost.lambda
std::transform( myvec.begin(), myvec.end(),
myvec.begin(), std::bind2nd( std::plus<double>(), 1.0 ) );
If you're interested in performing lots of math on vectors, you might want to look into the <valarray>
part of the standard library. It's basically a std::vector<>
designed for vectorial numerical computations (slices, math functions, point-wise operators, etc.).
The only part that really sucks is it doesn't have easy conversions to and from std::vector<>
.
The best way is to add std::transform()
and lambda expression.
#include <vector>
#include <algorithm>
std::vector<double> myVector;
double constantElement;
std::transform(myVector.begin(), myVector.end(), myVector.begin(), [&](auto& value){ return value+constantElement; });
精彩评论