How is this done in C++0x?
std::vector<double> myv1;
std::transform(myv1.begin(), myv1.end(), myv1.begin(),
std::bind1st(std::multiplies<double>(),3));
Original question and solution is here.
How is this done in C++0x?
std::vector<double> myv1;
std::transform(myv1.begin(), myv1.end(), myv1.begin(),
std::bind1st(std::multiplies<double>(),3));
Original question and solution is here.
std::transform(myv1.begin(), myv1.end(), myv1.begin(), [](double d) -> double { return d * 3; });
Like this:
vector<double> myv1;
transform(myv1.begin(), myv1.end(), myv1.begin(), [](double v)
{
return v*3.0;
}
);
Just do as Dario says:
for_each(begin(myv1), end(myv1), [](double& a) { a *= 3; });
for_each
is allowed to modify elements, saying it cannot is a myth.
Using a mutable approach, we can use for_each
to directly update the sequence elements through references.
for_each(begin(myv1), end(myv1), [](double& a) { a *= 3; });
for_each
is actually allowed to modify elements as it's called a "non-mutating" algorithm.
What that means is for_each
isn't allowed to alter the sequence it operates on (which refers to changes of the sequence structure - i.e. invalidating iterators). This doesn't mean we cannot modify the non-const elements of the vector as usual - the structure itself is left untouched by these operations.
The main original motivation for using that functional style for these cases in C++ was, "aaagh! iterator loops!", and C++0x removes that motivation with the range-based for statement. I know that part of the point of the question was to find out the lambda syntax, but I think the answer to the question "How is this done in C++0x?" is:
for(double &a : myv1) { a *= 3; }
There's no actual function object there, but if it helps you could pretend that { a *= 3; }
is a highly abbreviated lambda. For usability it amounts to the same thing either way, although the draft standard defines range-based for in terms of an equivalent for
loop.