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

I am in the process of learning C ++ but now I am stuck with an issue that really confuses me. The problem is that when I try to erase an element from the vector, the erase function does not erase the element that I wanted to erase, but instead removes the last element from the vector. I've recreated the problem with this piece of code, so it's easier for me to understand my problem than it would be with all my 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 as 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 it not working as I thought? If relevant, I am using the MinGW compiler for windows.

+3


source to share


3 answers


Once removed, you don't print the contents of the vector, just the loop variable.

Just replace the sections cout

with



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

      

and it will work at will.

+9


source


You are printing the loop variable, not the contents of the vector. For all instances:

Change

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

      



to

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

      

+1


source


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

      

it should be:

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

      

EDIT: I am late.

0


source







All Articles