7

我只是想知道是否有任何东西(在 c++11 或 boost 中)可以帮助我做这样的事情:

std::vector<int> v1 = {1, 2, 3};
std::vector<int> v2 = {2, 5, 4};
std::list<int> res;
algorithm(v1.begin(), v1.end(), v2.begin(), v2.end(), back_inserter(res), std::plus<int>());

结果当然应该是 {3, 7, 7} 而不是 std::plus 可以是任何 binary_function。

因此,如果有人有想法,请告诉我。

4

4 回答 4

12

std::vector只是为了好玩,我将指出and的替代方法std::transform。你可以std::valarray改用。

#include <valarray>
#include <iostream>

int main() { 
    std::valarray<int> a = {1, 2, 3};
    std::valarray<int> b = {2, 5, 4};

    std::valarray<int> c = a + b;    // look ma, no transform!

    for (int i=0; i<3; i++)
        std::cout << c[i] << "\t";
}

结果:

3       7       7

不幸的是,尽管将 valarray 加在一起的代码简单而干净,但 valarray 从未获得过广泛的欢迎。因此,我们留下了这种相当奇怪的情况,即使是上面那种让我觉得非常干净、直接和可读的代码,仍然几乎可以说是被混淆了,仅仅是因为很少有人习惯它。

于 2013-06-07T14:10:28.047 回答
9

您可以为此使用 5 参数重载std::transform。这需要一个二元仿函数来对两个范围的元素对进行操作:

std::transform(v1.begin(), 
               v1.end(), 
               v2.begin(), 
               back_inserter(res), 
               std::plus<int>());
于 2013-06-07T12:51:35.137 回答
4

std::transform是您正在寻找的。

于 2013-06-07T12:51:08.800 回答
4

std::transform ( http://en.cppreference.com/w/cpp/algorithm/transform ) 是您可能正在寻找的。

于 2013-06-07T12:51:18.167 回答