Search code examples
c++foreachstdelementwise-operations

How to use divides and for_each?


I have:

vector<double> ved1 = { 1,2,3,4,5,6,7,8,9,10 };
vector<double> ved2 = { 11,12,13,14,15,16,17,18,19,20 };
vector<double> ved3(10);

and I want to have ved3=ved3/2 but I can't get it correctly, the result is 2/ved3; How to use divides?

transform(ved1.begin(), ved1.end(), ved2.begin(), ved3.begin(), plus<double>());
transform(ved3.begin(), ved3.end(), ved3.begin(), bind1st(divides<double>(),2));`    

I want cos(ved2), but I cannot get it. What's wrong with my code?

double cos_1(double x) { return cos(x); }
for_each(ved2.begin(), ved2.end(), cos_1);

Solution

  • bind1st will bind 2 to the 1st argument of divides, and then transform will supply each element of ved3 to divides as the second argument. So the result will be divides(2, ved3[0]), divides(2, ved3[1]) and so on.

    If you want to calculate divides(ved3[...], 2) instead, use bind2nd(divides<double>(), 2). This way, 2 will be bound to the second argument, leaving the first one vacant for transform.