1

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);
einpoklum
  • 118,144
  • 57
  • 340
  • 684
Youshikyou
  • 365
  • 1
  • 8
  • 2
    how about using lambda? `transform(ved3.begin(), ved3.end(), ved3.begin(), [](double d){return d / 2;}));`? – Jarod42 Dec 22 '19 at 17:22
  • This appears to be two different questions. Ask one question per question. – Lightness Races in Orbit Dec 22 '19 at 17:36
  • Maybe you can try [`valarray`](https://en.cppreference.com/w/cpp/numeric/valarray). Though `valarray` provides very limited functionality, but if you only use the functionality it provides, you'll find it very convenient. – xskxzr Aug 03 '21 at 05:39

2 Answers2

2

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.

Anton
  • 3,113
  • 14
  • 12
1

How to use std::for_each to apply a cosine elementwise

std::for_each does not fill some output; or necessarily change the input container/range. It just applies an invocable object to each element of a range. If the function has no "side effects" - than the for_each would be useless. Specifically, in your case - you're computing the cosine of each value, but not doing anything with it.

If you want to change the values in-place, you'll need to specifically do that:

void apply_cos(double& x) { x = std::cos(x); }

// ...

for_each(ved2.begin(), ved2.end(), apply_cos);

or using a lambda expression:

for_each(ved2.begin(), ved2.end(), [](double& x) { x = cos(x); });

Note the use of a reference input to the function rather than a value: double& x, not double x. That means that when you change x in apply_cos(), the value in the input range to std::for_each changes.

einpoklum
  • 118,144
  • 57
  • 340
  • 684