Search code examples
c++mingwerase

vector::erase does not erase the desired element, but instead erases the last element from the vector


I've been working on learning c++, but now I'm stuck with a problem that really confuses me. The problem is that when i try to erase an element from a vector, the erase function does not erase the element that i wanted to be erased, but instead erases the last element from the vector. I recreated the problem with this piece of code, so that it's easier to understand my problem than it would be with my whole code:

#include <vector>
#include <iostream>

int main()
{
     std::vector<int> c;
     for(int i=0; i<=10; i++){
         c.push_back(i);
     }

    for (int i=0;i<c.size();i++) {
        std::cout << i << " ";
    }
    std::cout << '\n';

    c.erase(c.begin()+2);

    for (int i=0;i<c.size();i++) {
        std::cout << i << " ";
    }
    std::cout << '\n';

    c.erase(c.begin()+2, c.begin()+5);

    for (int i=0;i<c.size();i++) {
        std::cout << i << " ";
   }
    std::cout << '\n';

}

the result is not what is expected:

0 1 2 3 4 5 6 7 8 9 10
0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6

when I thought the result would be

0 1 2 3 4 5 6 7 8 9 10
0 1 3 4 5 6 7 8 9 10
0 1 2 7 8 9 10

Am I doing something completely wrong, or why is this not working as I thought it would? If it is relevant, I'm using the MinGW compiler for windows.


Solution

  • After deletion, you do not print the content of the vector but only the loop variable.

    Simply replace your cout sections by

    for (int i=0;i<c.size();i++) {
        std::cout << c[i] << " ";
       }
    

    and it will work as desired.