在向量中重复元素

Repeat elements in a vector

本文关键字:元素 向量      更新时间:2023-10-16

我有一个向量

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

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

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

编辑:事实上,如果我需要多次重复这些元素,比如1000个,显然我必须快速而轻便的东西?

我该怎么做?

这可能很棘手。如果要避免创建临时工作对象,则必须小心避免在运行时使迭代器失效。这应该这样做:

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';

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

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);

使用向量类的insert方法

v.insert(v.end(), v.begin(), v.end());

使用std::copy

std::vector<int> v = { 1 , 2, 3, 4, 5};
std::vector<int> r;
for (auto i = 0; i < 3; ++i) {
    std::copy(v.begin(), v.end(), std::back_inserter(r));
}
v.swap(r);