Re: divide all elements in a vector by a number
On Nov 15, 6:01 pm, "Victor Bazarov" <v.Abaza...@comAcast.net> wrote:
utab wrote:
Dear all,
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.
BOOST_FOREACH seemed the best option to me. But I wondered :)
Everybody is supposed to do their own homework.
V
--
Please remove capital 'A's when replying by e-mail
I do not respond to top-posted replies, please don't ask
Oops, you are not right since I did not paste any code :)
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
void print(double d)
{
cout << " " << d << endl;
}
int main()
{
vector<double> x;
for(double i=0;i!=10;++i)
x.push_back(i);
double max=*max_element(x.begin(),x.end());
cout << max << endl;
vector<double>::iterator iterx=x.begin();
for(;iterx!=x.end();++iterx)
{
if(fabs(max)>1e-6){ // just a pre-caution for divide by 0.
*iterx=*iterx/max;
}
}
for_each(x.begin(),x.end(),print);
return 0;
}
That was the question, without a loop, is this possible?
I could not find the answer in my references,
I made the example quickly, hope it is error free!
Rgds,