c++ - 如何在基于范围的 for 中使用多个容器?

标签 c++ loops stl iteration auto

我有多个不同类型的容器。
我想对所有容器中的所有元素执行相同的操作。
通常,这涉及多个具有重复代码的基于范围的 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';
}

demo

或者,range-v3的 zip View :

for(auto&& el : view::zip(v1, v2)) {
    std::cout << std::get<0>(el) << ", " << std::get<1>(el) << '\n';
}

demo


或者,您可以通过困难的方式从 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';
}

demo

关于c++ - 如何在基于范围的 for 中使用多个容器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40858591/

相关文章:

c++ - 在 vector 上调用 .end() 的复杂性是多少?

c++ - 如何正确使用 cv::triangulatePoints()

c++ - SFML 停留在主函数退出

python - 为什么x的内容消失了。关于 python 中正确性的推理?

bash - 在 Bash 中循环遍历字母表

c++ - 将 initializer_list 插入 std::vector 时出现 "Invalid iterator range"

c++ - Visual C++ 2010 中的 STL 映射实现和线程安全

c++ - 为什么我的程序的 objdump -D 看起来和 .S 不一样

c++ - 无法使用函数更改数组中的元素

java - 让应用程序等待几秒钟 Java