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

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

Multi variable range based for loop c++

问题

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

我有这样的代码 -

  1. class Result{
  2. ...
  3. ...
  4. };
  5. std::vector<Result> results;
  6. std::vector<Result> groundTruth(2);
  7. int gtIndex = 0;
  8. for(auto& r:results){
  9. auto gt = groundTruth[gtIndex];
  10. // compare r and gt
  11. gtIndex++;
  12. }

我使用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 -

  1. class Result{
  2. ...
  3. ...
  4. };
  5. std::vector&lt;Result&gt; results;
  6. std::vector&lt;Result&gt; groundTruth(2);
  7. int gtIndex = 0;
  8. for(auto&amp; r:results){
  9. auto gt = groundTruth[gtIndex];
  10. // compare r and gt
  11. gtIndex++;
  12. }

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元素的引用而不是数组索引来实现部分目标。

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

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

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

  1. check_sizes(results, groundTruth);
  2. auto it{ std::begin(groundTruth) };
  3. for (auto&amp; r : results) {
  4. auto&amp; g{ *it++ }; // r和g都是对Result的引用
  5. // 比较r和g
  6. if (r == g) {
  7. // ...
  8. }
  9. }
英文:

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:

  1. using result_vector = std::vector&lt;Result&gt;;
  2. void check_sizes( result_vector const&amp; v1, result_vector const&amp; v2 )
  3. {
  4. if (v1.size() != v2.size())
  5. throw std::runtime_error(&quot;Size mismatch&quot;);
  6. }

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

  1. check_sizes(results, groundTruth);
  2. auto it{ std::begin(groundTruth) };
  3. for (auto&amp; r : results) {
  4. auto&amp; g{ *it++ }; // r and g are both references to Result
  5. // compare r and g
  6. if (r == g) {
  7. // ...
  8. }
  9. }

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:

确定