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++ 的链式迭代器
基础教程推荐
- 运算符重载的基本规则和习语是什么? 2022-10-31
- 设计字符串本地化的最佳方法 2022-01-01
- C++ 程序在执行 std::string 分配时总是崩溃 2022-01-01
- 您如何将 CreateThread 用于属于类成员的函数? 2021-01-01
- C++ 标准:取消引用 NULL 指针以获取引用? 2021-01-01
- 如何定义双括号/双迭代器运算符,类似于向量的向量? 2022-01-01
- 如何在 C++ 中处理或避免堆栈溢出 2022-01-01
- 调用std::Package_TASK::Get_Future()时可能出现争用情况 2022-12-17
- C++,'if' 表达式中的变量声明 2021-01-01
- 什么是T&&(双与号)在 C++11 中是什么意思? 2022-11-04