erase element from vector

Nov 21, 2012 at 9:06pm
say I have a vector with 8(0-7) elements.
How do I delete the 4th element?

1
2
3
4
5
vec.erase(vec.begin() +4);

or

vec.erase(vec.begin() +3);


I've seen this code:
1
2
3
4
5
  // erase the 6th element
  myvector.erase (myvector.begin()+5);

  // erase the first 3 elements:
  myvector.erase (myvector.begin(),myvector.begin()+3);


in the second line they remove the 6th element by adding 5 to vec.begin()
but in the last line they add +3 to delete the first 3 elements. I got a bit confused there,so I decided to ask you guys :)
Last edited on Nov 21, 2012 at 9:07pm
Nov 21, 2012 at 9:12pm
In the second line, myvector.begin()+0 would be the 1st element, +1 would be the 2nd, +2 the 3rd, and so on. So to access the 4th element, it would be myvector.begin()+3.

In the last line, this is calling a different version of the same function (one that takes 2 parameters). The first parameter is the element to start at, while the second parameter is the element after the last one you want erased. So it will erase everything from the 1st element up to the 4th element, which is the first 3 elements.
Last edited on Nov 21, 2012 at 9:12pm
Topic archived. No new replies allowed.