英文:
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<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++.
答案1
得分: 1
我不知道有什么简单的方法来获得你想要的,但是,你可以通过使用对groundTruth元素的引用而不是数组索引来实现部分目标。
首先,你可能想要验证大小:
使用 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");
}
然后,你可以使用两到三行额外的模板代码来运行你的循环(如果你不需要检查大小则为两行):
check_sizes(results, groundTruth);
auto it{ std::begin(groundTruth) };
for (auto& r : results) {
auto& 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<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) {
// ...
}
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论