2016-11-16 39 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; 
} 

其實這是近正是C++編譯器11將創建,當你將使用拉姆達。

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_cast需要知道哪些過載的std::exp傳遞給std::transform編譯器。