### vector.erase() question

Hello!

I have a simple question about a vector operation.

Let's say we have this:
 ``1234567`` ``````vector numbers; numbers.push_back(0); numbers.push_back(10); numbers.push_back(20); numbers.push_back(30); numbers.push_back(40);``````

If I erase one of the number like so:
 `` `` ``numbers.erase(2);``

Does it set `number[2]` equal to 0 without changing the vector size,
or does it remove the int held in `number[2]` and decrement the vector's size by one?

Ultimately what I want to do is have a vector in which I would erase its content one by one,
and I want to check if it's empty with `if (numbers.empty())` so if its size is 0.

Last edited on
Before: { 0 10 20 30 40 } , size 5

`numbers.erase(numbers.begin() + 2);`

After: { 0 10 30 40 } , size 4
Last edited on
Okay, thank you Repeater this is exactly what I wanted to know!

Have a good day!
If I erase one of the number like so:
 `` `` `` numbers.erase(2);``

Then you will get a compiler error.

The erase function takes an iterator as a parameter. Iterators are a topic in their own right, but you can think of it as an object which behaves like a pointer.

See the reference page for erase():
http://www.cplusplus.com/reference/vector/vector/erase/

One possible syntax for your example would be:
 ``12`` `````` // erase one of the numbers numbers.erase(numbers.begin() + 2);``````
and it reduces the array size by 1.

(see the reference page for begin() as well).
http://www.cplusplus.com/reference/vector/vector/begin/

Example code below:
 ``123456789101112131415161718192021222324252627282930313233`` ``````#include #include #include using namespace std; void print(const vector & v) { cout << "size = " << v.size() << '\n'; for (int n : v) cout << setw(4) << n; cout << '\n'; } int main() { vector numbers; numbers.push_back(0); numbers.push_back(10); numbers.push_back(20); numbers.push_back(30); numbers.push_back(40); // Now print it out print(numbers); // erase one of the numbers numbers.erase(numbers.begin() + 2); print(numbers); }``````

Output:
 ```size = 5 0 10 20 30 40 size = 4 0 10 30 40 ```
Thank you Chervil for the detailed explanation and the sources. I was aware of the .size and .erase functions however I didn't know how .erase interacted with the vector size.

So to triple check if you do this:

`numbers.erase(number.begin(), number.end());`

`numbers.size()` should be equal to zero
and the content of `numbers` should be {}.

Is that correct?
Last edited on
 Is that correct?
Yes. (after correcting minor typing errors).

It's easy enough to check using the online compiler. If you look at my post above, to the top right of the code there is a gear icon. Click that and it takes you to a page where you can edit, compile and run the code:

http://cpp.sh/73km5
Thank you Chervil I will keep that in mind for later posts !
Topic archived. No new replies allowed.