代码之家  ›  专栏  ›  技术社区  ›  amit kumar

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

c++
  •  4
  • amit kumar  · 技术社区  · 16 年前

    增强范围库( http://www.boost.org/doc/libs/1_35_0/libs/range/index.html )允许我们将一对迭代器抽象到一个范围中。现在我想把两个范围合并为一个,即:

    给定两个范围r1和r2,定义r遍历[r1.begin()、r1.end()[然后是[r2.begin()、r2.end()[。有没有办法用R1和R2把r定义为一个范围?

    3 回复  |  直到 14 年前
        1
  •  6
  •   amit kumar    14 年前

    我又需要这个了,所以我看了看。有一种方法可以使用boost/range/join.hpp来确定两个范围。不幸的是,输出范围类型不包括在接口中:

    #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
            }
    }
    

    我使用编译器消息找到了输出类型。C++0X auto 也将与此相关。

        2
  •  1
  •   Peter Stuifzand    16 年前
    • 不能对两个范围调用两次函数吗?或者这种方法有问题吗?
    • 将这两个范围复制到一个容器中并传递它。
    • 编写自己的range类,这样它首先遍历r1,然后遍历r2。
        3
  •  0
  •   Roel    16 年前

    我认为您必须创建一个自定义迭代器,当到达r1.end()时,它将“回滚”r1.end()到r2.begin()。然后该迭代器的begin()和end()将组合到您的范围r中。afaik没有标准的boost函数可以提供这种行为。