Re: divide all elements in a vector by a number
Daniel T. wrote:
utab <umut.tabak@gmail.com> wrote:
I was wondering if I could divide all elements of a vector by the max
element of that vector.
I checked the STL references and found transform, for_each and lately
BOOST_FOREACH, but transform and for_each algorithms are not suited
since I have another argument to supply to the functions, namely
max_element. I wondered if this is possible or not through the
standard.
First find the max element of the vector (hint: there is an algorithm
for that.) Then transform each element by dividing it by that number.
For extra credit: With the proper use of functors, the whole thing can
be done in one line of code.
Make a stab at it and post it with this same subject. I'd love to see if
you can come up with it, and will help you out if you can at least get
close. :-)
Although there are mulitple ways of doing this in one line as an
academic exercise, I think performance and readiability wise, a 2 liner
is better for practical purposes. I don't doubt your intention but let's
not send out the wrong signal. :)
To the OP, do look up boost::lambda, suppose you already have the
maximum value in max_r, there is a succinct way to express your
algorithm through transform:
std::transform(from.begin(), from.end(), to.begin(), _1/max_r);
You can do in place transformation:
std::transform(from.begin(), from.end(), from.begin(), _1/max_r);
Fei