Home > Mobile >  Append vector to itself?
Append vector to itself?

Time:07-27

I'm trying to cloning the vector itself, for example if the vector is [2,3] it will become [2,3,2,3].

This is my program:

#include <iostream>
#include <vector>
using namespace std;

int main() 
{
    vector<int> a;
    
    a.push_back(2);
    a.push_back(3);
    
    for(int i: a)
    {
        a.push_back(i);
    }
        
    for(int i: a)
        cout << i << " ";
        
    return 0;
}

So I'm just pushing the elements to the vector itself but the output is [2,3,2,0]. I don't understand why.

Help me with this problem.

CodePudding user response:

Range-for is syntactic sugar for an iterator-based for-loop, and std::vector::push_back() can invalidate iterators like the ones being used internally by the range-for:

If the new size() is greater than capacity() then all iterators and references (including the past-the-end iterator) are invalidated. Otherwise only the past-the-end iterator is invalidated.

You can use std::copy() after a resize():

vector<int> a;
a.push_back(2);
a.push_back(3);

auto size = a.size();
a.resize(size * 2);
std::copy(a.begin(), a.begin()   size, a.begin()   size);

CodePudding user response:

Do not use range base iterators while changing the container you are iterating. In this case, just store the size of the vector before inserting and then use a regular index based loop.

int sz = a.size();

for(int i =0 ; i < sz ;   i)
{
   a.push_back(a[i]);
}

CodePudding user response:

You are iterating over the vector which is being changed at the same time.

//This is problematic
for(int i: a)
{
  a.push_back(i);
}

You can instead do it this way:

#include <iostream>
#include <vector>
using namespace std;

int main() 
{
    vector<int> a;
    
    a.push_back(2);
    a.push_back(3);
    
    vector<int> b = a; //Store contents in another vector
    
    for(int i: b)
    {
        a.push_back(i);
    }
        
    for(int i: a)
        cout << i << " ";
        
    return 0;
}
  • Related