Search code examples
c++pointersvectorerase

I cant erase the elements from a vector properly


So I am trying to append element from vector b into the end of vector a while erasing all the content in vector b. Below is my code, for some reason that erase is not working properly. Any input is appreciated Thx!!

void problem3(std::vector<int>& a, std::vector<int>& b){
    typedef std::vector<int>::iterator iter;
    int place_holder;
    for (iter i = b.begin();i !=b.end();i++){
        place_holder = *i;//use place hodler to store values temporairly 
        a.push_back(place_holder);//erase the elements from b
            b.erase(i);
        //std::cout<<b.size()<<'\n';
        //append at the end of a
    }
}

Solution

  • It's not a good idea to erase one element in the loop as the vector size is changing dynamically, which you will easily lose the correct index track.

    Instead, try to erase all b's elements once in the end:

    b.clear();
    

    P.S.: There is one easier way to append a vector to another by using std::vector::insert() so that all you need is:

    a.insert( a.end(), b.begin(), b.end() );
    b.clear();