C++ 的链式迭代器 [英] Chaining iterators for C++

查看:25
本文介绍了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++ 的链式迭代器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆