0

I have a vector

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

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

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?

How do I do it?

Nick X Tsui
  • 2,737
  • 6
  • 39
  • 73

3 Answers3

1

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);
Galik
  • 47,303
  • 4
  • 80
  • 117
0

Use the insert method of vector class

v.insert(v.end(), v.begin(), v.end());
Gordrim
  • 1
  • 1
  • 2
0

Use 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);
greedy52
  • 1,345
  • 9
  • 8
  • More on [Nice way to append a vector to itself](https://stackoverflow.com/questions/17636690/nice-way-to-append-a-vector-to-itself) – greedy52 Apr 19 '18 at 13:33