Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does a vector array resize after erasing one/more elements?

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?

like image 891
Kishaan92 Avatar asked Dec 19 '22 13:12

Kishaan92


1 Answers

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.

like image 95
gsamaras Avatar answered Dec 24 '22 00:12

gsamaras