1

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++.

9

1 Answer 1

1

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) {
        // ...
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.