4

Does vector.erase resize the vector object so that I can measure the reduced size with vector.size()?

for example;

vector<int> v(5);
v = {1,2,3,4,5};

and I want to delete 4 by;

v.erase(v.begin()+4);

Does my vector object v have a size of 4 now. In other words is v.size() == 4 after this operation?

W.F.
  • 13,888
  • 2
  • 34
  • 81
Kishaan92
  • 155
  • 2
  • 8

1 Answers1

11

Yes, size is decreased as you erase elements.


Don't be afraid to test yourself though, by writing a minimal example, like this :) :

#include <iostream>
#include <vector>

using namespace std;

int main()
{
    vector<int> v(5);
    v = {1,2,3,4,5};
    cout << v.size() << endl;
    v.erase(v.begin()+4);
    cout << v.size() << endl;
    return 0;
}

you would get:

gsamaras@gsamaras-A15:~$ g++ -Wall -std=c++0x main.cpp 
gsamaras@gsamaras-A15:~$ ./a.out 
5
4

And we would expect that right? I mean the ref says:

Return size

Returns the number of elements in the vector.

This is the number of actual objects held in the vector, which is not necessarily equal to its storage capacity.

gsamaras
  • 71,951
  • 46
  • 188
  • 305
  • Thanks! I was wondering whether that particular cell would be vacant or the consecutive elements would be shifted leftwards! – Kishaan92 Oct 02 '16 at 13:45
  • 1
    You are welcome @Kishaan92, make sure you *accept* the answer then! :) By the way, you should get used to writing minimal examples to test, when you are in doubt! :) – gsamaras Oct 02 '16 at 13:46
  • Yeah sure! I'll test it before posting it here next time. I'm a newbie to coding btw :) – Kishaan92 Oct 02 '16 at 14:09
  • I can sense that @Kishaan92, that's why I answered the question, otherwise I would have voted to close it. You see, I was pretty much like you at the start, but Stack Overflow (and some others) tought me how to overcome this fear! And now it's my turn... :) – gsamaras Oct 02 '16 at 14:11
  • Yeah, now I understand how to use Stack Overflow properly (i.e without getting any down votes ;) ) Hopefully I'll overcome my fear soon! :) – Kishaan92 Oct 02 '16 at 14:38