Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading