多变量范围-based for 循环 C++

huangapple go评论60阅读模式
英文:

Multi variable range based for loop c++

问题

可以在C++中使用两个并行迭代器编写基于范围的for循环吗?

我有这样的代码 -

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++;
}

我使用gtIndex访问groundTruth的元素。

问题:如何在C++的基于范围的for循环中包含地面真相迭代器?在Python中,我知道有zip函数可以实现这一点,但在C++中找不到类似的东西。

英文:

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

I have code like this -

class Result{
    ...
    ...
};

std::vector&lt;Result&gt; results;
std::vector&lt;Result&gt; groundTruth(2);

int gtIndex = 0;
for(auto&amp; 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++.

答案1

得分: 1

我不知道有什么简单的方法来获得你想要的,但是,你可以通过使用对groundTruth元素的引用而不是数组索引来实现部分目标。

首先,你可能想要验证大小:

使用 result_vector = std::vector&lt;Result&gt;;
void check_sizes( result_vector const&amp; v1, result_vector const&amp; v2 )
{
    if (v1.size() != v2.size())
        throw std::runtime_error(&quot;Size mismatch&quot;);
}

然后,你可以使用两到三行额外的模板代码来运行你的循环(如果你不需要检查大小则为两行):

check_sizes(results, groundTruth);
auto it{ std::begin(groundTruth) };
for (auto&amp; r : results) {
    auto&amp; g{ *it++ };     // r和g都是对Result的引用

    // 比较r和g
    if (r == g) {
        // ...
    }
}
英文:

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&lt;Result&gt;;
void check_sizes( result_vector const&amp; v1, result_vector const&amp; v2 )
{
    if (v1.size() != v2.size())
        throw std::runtime_error(&quot;Size mismatch&quot;);
}

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&amp; r : results) {
    auto&amp; g{ *it++ };     // r and g are both references to Result

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

huangapple
  • 本文由 发表于 2023年7月24日 19:38:59
  • 转载请务必保留本文链接:https://go.coder-hub.com/76754107.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定