std :: copy n个元素或到最后 [英] std::copy n elements or to the end

查看:71
本文介绍了std :: copy n个元素或到最后的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想复制最多N个元素.

I would like to copy up to N elements.

template< class InputIt, class Size, class OutputIt>
OutputIt myCopy_n(InputIt first, InputIt last, Size count, OutputIt result)
{
    Size c = count;
    while (first != last && c > 0) {
        *result++ = *first++;
        --c;
    }
    return result;
}

是否可以使用std函数来做到这一点?我还可以:

is there a way to do this with std functions? I could also:

template< class InputIt, class Size, class OutputIt>
OutputIt myCopy_n(InputIt first, InputIt last, Size count, OutputIt result)
{
    if(std::distance(first, last) > count)
        return std::copy_n(first,count,result);
    return std::copy(first,last,result);
}

但是,除了麻烦之外,它两次超出了范围(距离,复制).如果我使用转换迭代器或过滤器迭代器,则这些是对我的过滤器/转换函数的O(N)不必要的调用.

however, besides being cumbersome, it goes over the range twice (distance, copy). If i'm using a transform iterator, or filter iterator, those are O(N) unnecessary calls to my filter/transform function.

template <class InputIt, class OutputIt>
OutputIt copy_n_max(InputIt begin, InputIt end, OutputIt last, size_t count)
{
    return std::copy_if(begin, end, last, 
                        [&count](typename std::iterator_traits<InputIt>::reference)
                        { return count--> 0; });
}

int main()
{
    std::vector<int> v({1,2,3,4,5,6,7,8,9}), out;
    copy_n_max(v.begin(), v.end(), std::back_inserter(out), 40);
    for(int i : out) std::cout <<i << " ,";
}

输出1,2,3,4,5,6,7,8,9,

outputs 1,2,3,4,5,6,7,8,9,

但是,这将一直持续到结束,并且不会计算次数.因此,仍然有更多不必要的对我的filter/transform函数的调用...

however, this will continue until end, and not count times. so still, more unnecessary calls to my filter/transform function...

推荐答案

如果您可以访问整个数据结构及其大小,则可以使用以下内容:

If you have access to the whole data structure, and therefore its size, you can use the following:

std::vector<int> v1, v2;
std::copy_n(v2.begin(), std::min(NUM, v2.size()), std::back_inserter(v1));

如果您只能访问迭代器,那么我不知道如何仅使用std函数而不计算距离来执行此操作.对于随机访问的迭代器来说,这是便宜的,但是对于其他类型的迭代器来说,重复项是可行的.

If you have access to only iterators, I don't know how to do this using only std functions without calculating the distance. This is cheap for random-access iterators but duplicates work for other types.

std::vector<int>::iterator i_begin, i_end, o_begin;
std::copy_n(i_begin, std::min(NUM, std::distance(i_begin, i_end)), o_begin);

这篇关于std :: copy n个元素或到最后的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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