2016-11-16 7 views
3

std::transformstd::foreachを使用してこれを実装するにはどうすればよいですか? (C++ 11なし)std :: transformを使用してベクトルを指数化する

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; 
} 

ありがとうございました。

+2

関連:http://stackoverflow.com/questions/356950/c-functors-and-their-uses – NathanOliver

答えて

3

次のようになりますstd::transformを使用する:

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; 
} 

は、実際に、これはほぼ正確にあなたがラムダを使用する際に11コンパイラは、作成しますC++ものです。

1

ビット醜い溶液:

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_caststd::transformに渡すstd::expが過負荷コンパイラに指示する必要があります。

関連する問題