0

所以,我的一个类有以下重载:

DVector &operator+=(DVector const &other) {
    if (vector.size() >= other.vector.size()) throw up; // lol.

    std::for_each(other.vector.begin(); other.vector.end(), [](DVector const &pass) {
        // huh?
    });
}

因此,我们的想法是将两个向量的每个成员相加(嗯,每个DVector实例都包含一个std::vector<float>名为 的成员vector),例如:

如果我有一个DVector包含vector包含以下浮点数的成员:11.0, 23.5, 12.3,然后另一个包含14.0, 6.5, 7.7,则两者的总和应导致第一个向量保持25.0, 25.0, 25.0

问题:假设向量的大小不是问题,是否有任何方法可以遍历两个向量并仅使用一个迭代器对它们的成员求和,或者我只是被迫使用 a for (auto x: vector.size())

干杯,朱利安。

4

3 回答 3

3

这是一个 std::transfom 算法,它接受两个输入和一个输出迭代器。

我不知道您具体的矢量设计是如何构建的,但您应该能够根据需要修改以下内容。

 std::transform(input1.begin(), input1.end(),  //input1
                intput2.begin(),               //input2
                input1.begin(),                //output 
     [](double a, double b){
          return a+b;
     });

您也可以为您提供不同的输出迭代器operator +

这里有一些参考

http://en.cppreference.com/w/cpp/algorithm/transform

http://www.cplusplus.com/reference/algorithm/transform/

当你有不同的输出时, back_inserter 是你的朋友:

http://en.cppreference.com/w/cpp/iterator/back_inserter

于 2012-04-16T15:22:49.833 回答
2

迭代器与容器绑定,因此您不能使用单个迭代器。您必须使用一个索引或两个单独的迭代器。

于 2012-04-16T15:20:49.517 回答
2

如果我正确理解您的需求:

std::transform(vec1.begin(), vec1.end(), vec2.begin(), vec1.begin(),
    [](float lhs, float rhs) {
        return lhs + rhs;
    });
于 2012-04-16T15:22:08.070 回答