Pregunta

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
    }
}
¿Fue útil?

Solución

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

Otros consejos

This is because your iterator becomes invalid on erase. erase will return you the iterator pointing to the next element, e.g. i = b.erase(i). Please be aware, that you want to avoid i++ (or better: ++i) in the for-loop, otherwise elements might be skipped.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top