Attach a copy of std :: vector to the end

I am trying to make a copy of a row vector and add it to the end of my original vector, i.e. duplicating its contents. Example:

 Input : vector<string> s = {"abc", "def"}
 Output: vector<string> s = {"abc", "def", "abc", "def"}

I used the insert method, i.e.

s.insert(s.end(), s.begin(), s.end());

However, this shows compiler-specific results. In, LLVM clang, he gave me the expected answer.

With gcc he gave me

 Output: vector<string> s = {"abc", "def", "", ""}

I wonder why this happens and what is the safest way to achieve this vector duplication goal?

Here is the ideone.com link for the program above: http://ideone.com/40CH8q

+3
source share
4 answers

Although it is possible to do this 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]);

, ( ) ; , , . , "" : .

+5

, , vector::reserve(), . ( , push_back() .)

( vector::insert()), , , , :

#include <algorithm>
#include <iostream>
#include <iterator>
#include <string>
#include <vector>

using namespace std;

int main() {

  vector<string> s{"abc", "def"};

  auto size = s.size();

  s.reserve(2*size); // <-- This one is essential to ensure
                     //     no reallocation during insertion

  const string* first = s.data(); // using pointer, instead of iterator

  copy(first, first+size, back_inserter(s));

  for (const auto& e : s)
    cout << e << '\t';

  cout << endl;
}
+3

, , , reserve:

sv.reserve(sv.size() * 2);

This is because if redistribution occurs, iterators become invalid. You can check it yourself:

std::cout << sv.capacity() << "\n"; // 2

The new size will be larger than the capacity, so redistribution will occur.

0
source

It can be done like that.

vector<string> data = {"abc", "def"}; // Input String Vector
int len = data.size();
for(int i = 0; i < len; i++)
{
    data.push_back(data[i]); // Making Copy of String Vector
}

vector<string> data = {"abc", "def", "abc", "def"};
//Resultant String Vector
0
source

All Articles