Nice way to append a vector to itself

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


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.


I would do it like this:

#include <algorithm>
#include <vector>
#include <utility>

int main(int argc, char* argv[])
{
    std::vector<int> v1 = { 1, 2, 3, 4, 5 };

    {
        std::vector<int> v2(v1.begin(), v1.end());
        std::copy(v1.begin(), v1.end(), std::back_inserter(v2));
        std::swap(v1, v2);
    }

    return 0;
}

EDIT: I added a slightly more efficient version.

#include <algorithm>
#include <vector>
#include <utility>

int main(int argc, char* argv[])
{
    std::vector<int> v1 = { 1, 2, 3, 4, 5 };

    {
        typedef std::move_iterator<decltype(v1)::iterator> VecMoveIter;
        std::vector<int> v2(v1);
        std::copy(VecMoveIter(v1.begin()), VecMoveIter(v1.end()), std::back_inserter(v2));
        v1 = std::move(v2);
    }

    return 0;
}