在向量中重复元素

时间:2018-04-19 13:04:33

标签: c++ vector

我有一个载体

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

我想重复矢量中的元素,比如3次,这样矢量becoms

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

编辑:事实上,如果我需要多次重复这些元素,比如1000,显然我必须快速轻松地提供一些东西?

我该怎么做?

3 个答案:

答案 0 :(得分:1)

这可能很棘手。如果你想避免创建一个临时工作对象,你必须小心避免在你去的时候使迭代器失效。这应该这样做:

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

答案 1 :(得分:0)

使用vector class

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

答案 2 :(得分:0)

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