2016-11-16 36 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编译器。