"Przycinanie" wektora, std::vector

"Przycinanie" wektora, std::vector
AK
  • Rejestracja:ponad 6 lat
  • Ostatnio:około 6 lat
  • Postów:2
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ć.

AP
  • Rejestracja:około 6 lat
  • Ostatnio:około 6 lat
  • Postów:6
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.

tajny_agent
  • Rejestracja:ponad 11 lat
  • Ostatnio:ponad rok
  • Postów:1340
3

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

Kopiuj
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

"I love C++. It's the best language in the world right now for me to write the code that i need and want to write"
~ Herb Sutter
edytowany 1x, ostatnio: tajny_agent
twonek
  • Rejestracja:prawie 11 lat
  • Ostatnio:prawie 2 lata
  • Postów:2500
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).

RE
  • Rejestracja:ponad 18 lat
  • Ostatnio:około 10 godzin
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/


We are the 4p. Existence, as you know it, is over. We will add your biological and technological distinctiveness to our own. Resistance is futile
edytowany 2x, ostatnio: revcorey

Zarejestruj się i dołącz do największej społeczności programistów w Polsce.

Otrzymaj wsparcie, dziel się wiedzą i rozwijaj swoje umiejętności z najlepszymi.