追加范围在循环中 [英] Appending ranges in loop

查看:227
本文介绍了追加范围在循环中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将由函数返回的范围连接到一个大范围中。请考虑以下代码:

I would like to concatenate ranges returned by function into one big range.Consider following code:

some_type_i_cant_figure_out bar() {
    typedef std::vector<int>::const_iterator iter;
    std::vector<int> aaa;
    /* fill some data into aaa*/
    some_type_i_cant_figure_out cc;
    for (int i = 0; i < aaa.size(); ++i) {
    std::pair<iter, iter> bbb = foo(aaa, i);
    ccc = boost::join(ccc, bbb);
    }
    return ccc;
}

我想达到的效果:

aaa向量是巨大的,foo可能返回相当大的范围。当然,我可以创建范围内的所有元素的副本到新的整数向量,并返回它。它是低效的,浪费内存和时间。所以我想返回一个boost :: joined_range。在最坏的情况下,我可以用范围向量,但它会太简单,不那么优雅:)
除了join_range isnt默认构造(这是一个有问题的这个示例实现)什么将返回值类型? (ccc)类型和什么是正确和优雅的方式来实现上述?

What I'm trying to achieve:
The aaa vector is huge and foo may return quite big ranges. Of course I can just create copies of all elements in range into new vector of integers and return it. It is inefficient, wasting memory and time. So I would like return one boost::joined_range. In worst case, I can live with vector of ranges, but it would be too simple and not that elegant :) besides the joined_range isnt default constructible (which is a problematic for this example implementation) what would be the return value type? the temp variable (ccc) type and what would be the correct and elegant way to achieve the above?

推荐答案

首先,您的代码的最终结果看起来类似于

First off, the end result of your code would appear to be similar to just

auto cc(aaa);
boost::stable_sort(cc);

(假设你的示例代码中 aaa 包含范围 [0..size() - 1)中的整数

(Assuming, from your sample code, that aaa contains integers in the range [0..size()-1))

只需使用反向插入迭代器:

If you can afford to simply copy, just use a backinsert iterator:

std::vector<int> cc;
for (size_t i = 0; i < aaa.size(); ++i)
    boost::copy(boost::equal_range(aaa, i), back_inserter(cc));

否则,可以使用 any_range

boost::any_range<int, boost::forward_traversal_tag, int> r;
for (size_t i = 0; i < aaa.size(); ++i)
    r = boost::join(r, boost::equal_range(aaa, i));

Live on Coliru

#include <boost/range/any_range.hpp>
#include <boost/range/join.hpp>
#include <boost/range/algorithm.hpp>
#include <iostream>

int main() {
    std::vector<int> const aaa { 1,1,1,4,5,5,9,42,42,42,42,42,42 };

    boost::any_range<int, boost::forward_traversal_tag, int> r;
    for (size_t i = 0; i < aaa.size(); ++i)
        r = boost::join(r, boost::equal_range(aaa, i));

    boost::copy(r, std::ostream_iterator<int>(std::cout << "result: ", " "));
}

列印

result: 1 1 1 4 5 5 9

这篇关于追加范围在循环中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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