使用标准 C++ 同时迭代 std::vectors

Iterating std::vectors simultaneously using standard C++

我是 C++ 的新手,因此在完成某项任务时需要一些帮助。问题是,我必须同时迭代三个或更多向量,如下所示:

#include <vector>
#include <iostream>
#include <string>
#include <boost/range/combine.hpp>

using namespace std;


int main(int, char**) {

vector<string> questions = {"Planet", "Rocket", "Galaxy"};
vector<string> answers = {"Planet", "Saturn", "Star"};

vector<int> count = { 12, 34, 79};
vector<int> score = { 324, 956, 289};

vector<int> result;
vector<int> subscore;

string a, q;
int c, s;
for ( const string q : questions ) {
    int match = 0;
    for( auto tuple : boost::combine(answers, count) ) {
       boost::tie(a,c) = tuple;
       if( q.substr(0,2) == a.substr(0,2)) {std::cout << q.substr(0,3) << " " << a.substr(0,3) << endl; match = c;  }
       else cout << "No match!" << '\n';
            }
    if( match ) { result.push_back(match); }
    else result.push_back(0); subscore.push_back(0);

这种方法有效,但我不能在我们使用的框架中使用它。

也许这里有人可以向我指出一个类似的解决方案,该解决方案不依赖于提升但仍然有效。

非常感谢!

你可以使用旧索引:

auto size = std::min( answers.size(), count.size() ); // or at least assert that size is equal
for( size_t i = 0; i < size; ++i ) {
   const auto &a = answers[i];
   const auto c = count[i];
   // .. same as before

请注意,这样您可能会避免每次迭代制作 2 个 std::string 副本 - answers -> tuple -> a

这似乎是 transform 所以在 C++ 中你可以使用 std::transform... 例如:

#include <vector>
#include <iostream>
#include <string>
#include <algorithm>

using namespace std;

int main(int, char**) {
    vector<string> questions = {"Planet", "Rocket", "Galaxy"};
    vector<string> answers = {"Planet", "Saturn", "Star"};

    vector<int> count = { 12, 34, 79};

    vector<int> result;

    for(const auto& q : questions)
    {
        transform(begin(answers), end(answers), begin(count), back_inserter(result),
                  [&q](const auto& answer, auto count)
        {
            if (q.substr(0, 2) == answer.substr(0, 2))
            {
                std::cout << q.substr(0,3) << " " << answer.substr(0,3) << endl;
                return count;
            }
            else
                cout << "No Match!" << endl;

            return 0;
        });
    }
}

现在 results 向量包含所有结果。 back_inserter 用于动态增长 result std::vector