Append a copy of std::vector to the end of itself

c++, clang, gcc, iterator, llvm

Solution

Although it can possibly be done with iterators, a safe alternative is to avoid them:

size_t size = v.size();  // Of course we shouldn't access .size() in the loop...
v.reserve(size * 2);     // Preallocation. Thanks @Ali for this performance hint
for (size_t i = 0; i < size; ++i)
    v.push_back(v[i]);

In general, working with iterators while also modifying the data structure (not only its elements) is dangerous; you should read carefully when iterators are invalidated and when it's safe to reuse old iterators after a modification. Thus, it sometimes makes sense to use the "old" method to iterate through a random-access sequence: using an index variable.

Problem

I am trying to make a copy of a vector of string and append it to the end of its original vector, i.e. duplicating its contents. Example: ``` Input : vector<string> s = {"abc", "def"} Output: vector<string> s = {"abc", "def", "abc", "def"} ``` I was using the insert method, i.e. ``` s.insert(s.end(), s.begin(), s.end()); ``` However, this exhibits compiler-dependent results. In, LLVM clang, it gave me the expected answer. With GCC it gave me ``` Output: vector<string> s = {"abc", "def", "", ""} ``` I am wondering why this happens and what's the safest way to achieve this vector duplication goal? Here is the ideone.com link for the program above: http://ideone.com/40CH8q

Original source

Related problems