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));
std::add_constantdoesn't exist is because it's pretty easy to write your own. C++ isn't a functional language, so doing stuff like this is a little clunky. - Michael Kristofikforloop for large vectors, thanks to compiler inlining. To parallelize the "add 1 to every element" operation you're going to need a separate library or custom solution tuned to your hardware. Remember: make sure you profile it before you decide it's too slow. - Michael Kristofik