Chaining iterators for C++(C++ 的链式迭代器)
问题描述
Python 的 itertools 实现了一个 chain 迭代器,它本质上连接了许多不同的迭代器提供来自单个迭代器的所有内容.
Python's itertools implement a chain iterator which essentially concatenates a number of different iterators to provide everything from single iterator.
C++ 中有类似的东西吗?快速浏览一下 boost 库并没有发现类似的东西,这让我很惊讶.这个功能很难实现吗?
Is there something similar in C++ ? A quick look at the boost libraries didn't reveal something similar, which is quite surprising to me. Is it difficult to implement this functionality?
推荐答案
在调查类似问题时遇到了这个问题.
Came across this question while investigating for a similar problem.
即使问题很老,现在在 C++ 11 和 boost 1.54 时代,使用 Boost.Range 库.它具有 join
-function,可以将两个范围合并为一个范围.在这里你可能会招致性能损失,作为最低通用范围概念(即 Single Pass Range 或 Forward Range 等)用作新范围的类别,在迭代期间,可能会检查迭代器是否需要跳转到新范围,但您的代码可以轻松编写为:
Even if the question is old, now in the time of C++ 11 and boost 1.54 it is pretty easy to do using the Boost.Range library. It features a join
-function, which can join two ranges into a single one. Here you might incur performance penalties, as the lowest common range concept (i.e. Single Pass Range or Forward Range etc.) is used as new range's category and during the iteration the iterator might be checked if it needs to jump over to the new range, but your code can be easily written like:
#include <boost/range/join.hpp>
#include <iostream>
#include <vector>
#include <deque>
int main()
{
std::deque<int> deq = {0,1,2,3,4};
std::vector<int> vec = {5,6,7,8,9};
for(auto i : boost::join(deq,vec))
std::cout << "i is: " << i << std::endl;
return 0;
}
这篇关于C++ 的链式迭代器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:C++ 的链式迭代器


基础教程推荐
- 我有静态或动态 boost 库吗? 2021-01-01
- 这个宏可以转换成函数吗? 2022-01-01
- 如何将 std::pair 的排序 std::list 转换为 std::map 2022-01-01
- 常量变量在标题中不起作用 2021-01-01
- 如何在 C++ 中初始化静态常量成员? 2022-01-01
- 如何通过C程序打开命令提示符Cmd 2022-12-09
- 如何检查GTK+3.0中的小部件类型? 2022-11-30
- 静态库、静态链接动态库和动态链接动态库的 .lib 文件里面是什么? 2021-01-01
- 在 C++ 中计算滚动/移动平均值 2021-01-01
- C++结构和函数声明。为什么它不能编译? 2022-11-07