Claudiordgz
Claudiordgz

Reputation: 3049

Dividing each element in a container between a given number C++

I was multiplying each container against another number so I did the following:

local_it begin = magnitudesBegin;
std::advance(begin , 2);
local_it end  = magnitudesBegin;
std::advance(end, 14);
std::transform(begin, end, firstHalf.begin(),
  std::bind1st(std::multiplies<double>(),100));

It worked wonders, problem is when doing the same to divide between another container. Here is a working example of my problem:

const std::size_t stabilitySize = 13;
boost::array<double,stabilitySize> secondHalf;
double fundamental = 707;
boost::array<double, stabilitySize> indexes = {{3,4,5,6,7,8,9,10,11,12,13,14,15}};
std::transform(indexes.begin(), indexes.end(), secondHalf.begin(),
  std::bind1st(std::divides<double>(),fundamental));

It does divide the container. But instead of dividing each element in the array against 707 it divides 707 between each element in the array.

Upvotes: 1

Views: 1837

Answers (3)

leemes
leemes

Reputation: 45665

If the number 707.0 is something like a fundamental constant, and a division can be seen as a "conversion", let's call it "x to y" (I don't know what your numbers are representing, so replace this by meaningful words). It would be nice to wrap this "x to y" conversion in a free-standing function for re-usability. Then, use this function on std::transform.

double x_to_y(double x) {
    return x / 707.0;
}
...
std::transform(..., x_to_y);

If you had C++11 available, or want to use another lambda-library, another option is to write this in-line where being used. You might find this syntax more readable like parameter binding using bind2nd:

std::transform(..., _1 / 707.0);  // when using boost::lambda

Upvotes: 0

std::bind1st(std::divides<double>(),fundamental)

The code above takes a functor std::divides<double> that takes two arguments and fixes the value of the first argument to be fundamental. That is it fixes the numerator of the operation and you get the expected result. If you want to bind fundamental to be the denominator, use std::bind2nd.

Upvotes: 4

fatihk
fatihk

Reputation: 7919

you can try the following , divide has a completely different operation than multiply, it just divides a constant number by all your elements

 std::bind1st(std::multiplies<double>(),1.0/707.0));

Upvotes: 2

Related Questions