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++ 的链式迭代器
基础教程推荐
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- CString 到 char* 2021-01-01
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
