重复向量中的元素 [英] Repeat elements in a vector

查看:44
本文介绍了重复向量中的元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个向量

vector<int>v = {1,2,3,4,5};

我想重复向量中的元素,比如说 3 次,这样向量就变成了

I'd like to repeat the elements in the vector for, say, 3 times, such that the vector becoms

v = {1,2,3,4,5, 1,2,3,4,5, 1,2,3,4,5};

编辑:事实上,如果我需要多次重复元素,比如 1000 次,显然我必须快速而轻松地来?

EDIT: In fact, if I need to repeat the elements for many times, say 1000, obviously I have to come with something quick and light?

我该怎么做?

推荐答案

这可能很棘手.如果您想避免创建临时工作对象,您必须小心避免在执行过程中使迭代器失效.应该这样做:

This can be tricky. If you want to avoid creating a temporary working object you have to be careful to avoid invalidating iterators as you go. This should do it:

std::vector<int> v = {1, 2, 3, 4, 5};

// to avoid invalidating iterators, preallocate the memory
v.reserve(v.size() * 3);

// remember the end of the range to be duplicated
// (this is the iterator we don't want to invalidate)
auto end = std::end(v);

// insert two duplicates
v.insert(std::end(v), std::begin(v), end);
v.insert(std::end(v), std::begin(v), end);

for(auto i: v)
    std::cout << i << '\n';

更一般地,您可以修改它以添加多个重复项,如下所示:

More generally you could modify this to add multiple duplicates like this:

std::vector<int> v = {1, 2, 3, 4, 5};

std::size_t const no_of_duplicates = 1000;

// to avoid invalidating iterators, preallocate the memory
v.reserve(v.size() * no_of_duplicates);

// remember the end of the range to be duplicated
// (this is the iterator we don't want to invalidate)
auto end = std::end(v);

// insert duplicates (start from one because already have the first)
for(std::size_t i = 1; i < no_of_duplicates; ++i)
    v.insert(std::end(v), std::begin(v), end);

这篇关于重复向量中的元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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