"Przycinanie" wektora, std::vector

0

Jak wygląda zmiana rozmiaru wektora po usunięciu elementu?
Dla przykładu: mam 5 elementów w wektorze. Wywołuję vector.erase(vector.begin()+3) co usuwa element o indeksie 3.
Czy po takiej operacji vector sam zmniejsza się o ten element czy w tym miejscu zostaje "dziura" a wektor nadal ma rozmiar 5 elementów i trzeba np zrobić resize lub shrink_to_fit?
Szukałem informacji tutaj ale nie doczytałem się tego co chciałem wiedzieć.

0

Sam się zmniejsza a... an iterator is pointing to the new location of the element that followed the last element erased by the function call. This is the container end if the operation erased the last element in the sequence.

3

Zależy co rozumiesz przez 'zmniejszanie się' wektora. Jeśli chodzi Ci o zwalnianie pamięci to nie.

vector<int> vec(100, 5);   // -> 100 elementów o wartości 5
vec.clear();  // -> usunięcie wszystkich elementów
cout << vec.size();  // -> 0
cout << vec.capacity(); // -> 100
2

Z linka który sam podałeś wystarczy kliknąć w erase: http://www.cplusplus.com/reference/vector/vector/erase/

Removes from the vector either a single element (position) or a range of elements ([first,last)).

This effectively reduces the container size by the number of elements removed, which are destroyed.

Because vectors use an array as their underlying storage, erasing elements in positions other than the vector end causes the container to relocate all the elements after the segment erased to their new positions. This is generally an inefficient operation compared to the one performed for the same operation by other kinds of sequence containers (such as list or forward_list).

0

oprócz tego co wyżej od kolegi to proszę to czego potrzebujesz(czasami)
http://www.cplusplus.com/reference/vector/vector/shrink_to_fit/

1 użytkowników online, w tym zalogowanych: 0, gości: 1