Concatenate 2 vectors

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.

>Solution :

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

Leave a Reply