Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Erase specific element from a vector is not working

Tags:

c++

vector

// erasing from vector
#include <iostream>
#include <vector>

int main ()
{
  std::vector<int> myvector;

  // set some values (from 1 to 10)
  for (int i=1; i<=10; i++) myvector.push_back(i);

  //First for loop
  for(int i=myvector.size()-1;i>=0;i--)
  {
      myvector.erase(myvector.begin()+i);
  }

  //second for loop which isn't working 

//   for(int i=0;i<myvector.size();i++)
//   {
//       myvector.erase(myvector.begin()+i);
//   }



  std::cout << "myvector contains:";
  for (unsigned i=0; i<myvector.size(); ++i)
    std::cout << ' ' << myvector[i];
  std::cout << '\n';

  return 0;
}

In this code I have two for loops doing the exact same thing. The first one is working while the second one which is commented isn't, and the output if I used the commented for loop is:

myvector contains: 2 4 6 8 10                                                                                             

Any idea why this is happening?

like image 468
OmarBakr Avatar asked Mar 28 '26 08:03

OmarBakr


1 Answers

It is because in the condition you call myvector.size() which will return smaller and smaller number since your vector is shrinking by each iteration.

In the first version you only call it once to initialize i that is why there is no problem. But in the second version it is called in each iteration.

like image 151
Eraklon Avatar answered Mar 29 '26 20:03

Eraklon



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!