Wann sollte man in der STL Vektor vs. Liste wählen?
Laut Effective STL sollte der Vektorcontainer die Standardauswahl für Sequenzen sein. Diese Empfehlung bedarf jedoch weiterer Klarstellung.
Vektor vs. Liste: Hauptunterschiede
Um den Unterschied zwischen Vektoren und Listen zu verstehen, betrachten Sie die folgende Tabelle:
Feature | Vector | List |
---|---|---|
Memory allocation | Contiguous | Non-contiguous |
Storage overhead | Pre-allocates space | Constant memory overhead |
Element space | No extra pointers | Extra space for node (pointers to next/previous) |
Memory reallocation | Can reallocate memory for entire vector | Never reallocates memory for entire list |
Insertion efficiency | O(1) at end, O(n) elsewhere | O(1) anywhere |
Erasure efficiency | O(1) at end, O(n) elsewhere | O(1) always |
Random access | Supported | Not supported |
Iterator validity | Invalidated after additions/removals | Remains valid after additions/removals |
Array access | Underlying array easily obtained | No underlying array available |
Wann eine Liste vorzuziehen sein kann
Während Vektoren es sind Listen sind im Allgemeinen effizienter und können in bestimmten Szenarien die bessere Wahl sein:
Das obige ist der detaillierte Inhalt vonVektor vs. Liste im STL: Wann sollten Sie sich für welches entscheiden?. Für weitere Informationen folgen Sie bitte anderen verwandten Artikeln auf der PHP chinesischen Website!