user3294195 user3294195 - 21 days ago 6
C++ Question

Exponentiate a vector using std::transform

How do I implement this using

std::transform
and
std::foreach
? (without C++11)

std::vector<double> exp_c(const std::vector<double>& x) {
const int n = x.size();
std::vector<double> y(n);
for (int i = 0; i < n; i++) {
y[i] = std::exp(x[i]);
}
return y;
}


Thanks.

Answer

Using std::transform it would look as follows:

struct op { double operator() (double d) const { return std::exp(d); } };
std::vector<double> exp_c(const std::vector<double>& x) {
  const int n = x.size();
  std::vector<double> y(n);  
  std::transform(x.begin(), x.end(), y.begin(), op());
  return y;
}

actually this is nearly exactly what c++11 compiler would create, when you would use lambda.