简体   繁体   English

增强范围库:按顺序遍历两个范围

[英]Boost Range Library: Traversing Two Ranges Sequentially

Boost range library ( http://www.boost.org/doc/libs/1_35_0/libs/range/index.html ) allows us to abstract a pair of iterators into a range. Boost范围库( http://www.boost.org/doc/libs/1_35_0/libs/range/index.html )允许我们将一对迭代器抽象为一个范围。 Now I want to combine two ranges into one, viz: 现在我想将两个范围合并为一个,即:

given two ranges r1 and r2, define r which traverses [r1.begin(), r1.end()[ and then [r2.begin(), r2.end()[. 给定两个范围r1和r2,定义r遍历[r1.begin(),r1.end()[然后[r2.begin(),r2.end()[。 Is there some way to define r as a range using r1 and r2? 有没有办法使用r1和r2将r定义为范围?

I needed this again so I had a second look. 我再次需要这个,所以我再看看。 There is a way to concat two ranges using boost/range/join.hpp. 有一种方法可以使用boost / range / join.hpp来连接两个范围。 Unluckily the output range type is not included in the interface: 不幸的是,输出范围类型不包含在界面中:

#include "boost/range/join.hpp"
#include "boost/foreach.hpp"
#include <iostream>

int main() {
        int a[] = {1, 2, 3, 4};
        int b[] = {7, 2, 3, 4};

        boost::iterator_range<int*> ai(&a[0], &a[4]);
        boost::iterator_range<int*> bi(&b[0], &b[4]);
        boost::iterator_range<
           boost::range_detail::
           join_iterator<int*, int*, int, int&, 
           boost::random_access_traversal_tag> > ci = boost::join(ai, bi); 

        BOOST_FOREACH(int& i, ci) {
                std::cout << i; //prints 12347234
        }
}

I found the output type using the compiler messages. 我使用编译器消息找到了输出类型。 C++0x auto will be relevant there as well. C ++ 0x auto也与此相关。

  • Can't you call the function twice, once for both ranges? 你不能两次调用这个函数,一次是两个范围吗? Or are there problems with this approach? 或者这种方法有问题吗?
  • Copy the two ranges into one container and pass that. 将两个范围复制到一个容器中并传递它。
  • Write your own range class, so it iterates through r1 first and and through r2 second. 编写自己的范围类,因此它首先遍历r1并通过r2秒迭代。

I think you'd have to make a custom iterator that will 'roll over' r1.end() to r2.begin() when r1.end() is reached. 我认为你必须制作一个自定义迭代器,当达到r1.end()时,它会将r1.end()翻转到r2.begin()。 Begin() and end() of that iterator would then be combined into your range r. 然后,该迭代器的Begin()和end()将合并到您的范围r中。 AFAIK there is no standard boost function that will give you this behavior. AFAIK没有标准的提升功能会给你这种行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM