我有多个不同类型的容器。
我想对所有容器中的所有元素执行相同的操作。
通常,这涉及多个具有重复代码的基于范围的 for 循环:
#include <iostream>
#include <vector>
#include <set>
int main() {
//containers
std::vector<int> v1{1,2,3,4,5};
std::set<float> v2{6,7,8,9,10};
//perform iterations
for (auto & it: v1){
std::cout << it << ' ';
}
for (auto & it: v2){
std::cout << it << ' ';
}
}
我希望能够改为这样做,
通过为相同的基于范围的 for 循环提供多个容器。
这当然行不通:
for (auto & it: v1,v2){
std::cout << it << ' ';
}
是否有我可以用来实现此目的的库解决方案?
最佳答案
您可以使用 boost range 的 combine
:
for(auto&& el : boost::combine(v1, v2)) {
std::cout << boost::get<0>(el) << ", " << boost::get<1>(el) << '\n';
}
或者,range-v3的 zip View :
for(auto&& el : view::zip(v1, v2)) {
std::cout << std::get<0>(el) << ", " << std::get<1>(el) << '\n';
}
或者,您可以通过困难的方式从 zip 迭代器创建一个范围:
auto b = boost::make_zip_iterator(boost::make_tuple(v1.begin(), v2.begin()));
auto e = boost::make_zip_iterator(boost::make_tuple(v1.end(), v2.end()));
for(auto&& tup : boost::make_iterator_range(b, e)) {
std::cout << boost::get<0>(tup) << ", " << boost::get<1>(tup) << '\n';
}
关于c++ - 如何在基于范围的 for 中使用多个容器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40858591/