Nitron_707
Nitron_707

Reputation: 371

Multi variable range based for loop c++

Can I write a range based for loop in c++ with two parallel iterators

I have code like this -

class Result{
    ...
    ...
};

std::vector<Result> results;
std::vector<Result> groundTruth(2);

int gtIndex = 0;
for(auto& r:results){
    auto gt = groundTruth[gtIndex];
    // compare r and gt

    gtIndex++;
}

I access elements from the groundTruth using gtIndex.

Question : How do I include the ground truth iterator in the range based for loop in C++. In python I am aware of zip function which does this, but could not find anything like that in C++.

Upvotes: 1

Views: 114

Answers (1)

tbxfreeware
tbxfreeware

Reputation: 2206

I do not know any easy way to get what you want, however, you can get halfway there by using a reference to the elements of groundTruth instead array indexing.

First, you may want to verify sizes:

using result_vector = std::vector<Result>;
void check_sizes( result_vector const& v1, result_vector const& v2 )
{
    if (v1.size() != v2.size())
        throw std::runtime_error("Size mismatch");
}

Then you can run your loop with just two or three extra lines of boilerplate (two if you do not need to check sizes):

check_sizes(results, groundTruth);
auto it{ std::begin(groundTruth) };
for (auto& r : results) {
    auto& g{ *it++ };     // r and g are both references to Result

    // compare r and g
    if (r == g) {
        // ...
    }
}

Upvotes: 1

Related Questions