3

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.

Edgar Rokjān
  • 17,245
  • 4
  • 40
  • 67
user3294195
  • 1,748
  • 1
  • 19
  • 36

2 Answers2

3

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.

marcinj
  • 48,511
  • 9
  • 79
  • 100
1

A bit ugly solution:

std::vector<double> exp_c(const std::vector<double>& x)
{
    std::vector<double> y;
    y.reserve(x.size());
    std::transform(x.begin(), x.end(), std::back_inserter(y),
                   static_cast<double(*)(double)>(std::exp));
    return y;
}

static_cast is necessary to tell the compiler which overload of std::exp to pass to std::transform.

Oleg Andriyanov
  • 5,069
  • 1
  • 22
  • 36