Nice way to append a vector to itself
c++, c++11, stdvector, stl
Solution
Wow. So many answers that are close, none with all the right pieces. You need both `resize` (or `reserve`) and `copy_n`, along with remembering the original size.
auto old_count = xx.size();
xx.resize(2 * old_count);
std::copy_n(xx.begin(), old_count, xx.begin() + old_count);
or
auto old_count = xx.size();
xx.reserve(2 * old_count);
std::copy_n(xx.begin(), old_count, std::back_inserter(xx));
When using `reserve`, `copy_n` is required because the `end()` iterator points one element past the end... which means it also is not "before the insertion point" of the first insertion, and becomes invalid.
23.3.6.5 `[vector.modifiers]` promises that for `insert` and `push_back`:
Remarks: Causes reallocation if the new size is greater than the old capacity. If no reallocation happens, all the iterators and references before the insertion point remain valid. If an exception is thrown other than by the copy constructor, move constructor, assignment operator, or move assignment operator of T or by any InputIterator operation there are no effects. If an exception is thrown by the move constructor of a non-CopyInsertable T, the effects are unspecified.
Problem
I want to duplicate the contents of the vector and want them to be appended at the end of the original vector i.e. `v[i]=v[i+n] for i=0,2,...,n-1` I am looking for a nice way to do it, not with a loop. I saw `std::vector::insert` but the iterative version forbids a iterator to `*this`(i.e behaviour is undefined). I also tried `std::copy` as follows(but it resulted in segmentation fault): `copy( xx.begin(), xx.end(), xx.end());`