Sobes.tech
Junior — Middle

What are the typical problems and limitations faced when using std::vector in C++?

sobes.tech AI

Answer from AI

Typical problems and limitations when using std::vector in C++:

  • Reallocation of memory: When adding elements, the vector may reallocate memory, copying all elements to a new buffer, which can be costly in terms of time.
  • Iterators and pointers may become invalid: When reallocation occurs, all iterators, pointers, and references to vector elements become invalid.
  • Type restrictions: Elements of the vector must be copyable or movable.
  • Inefficiency when inserting/removing in the middle: Inserting or deleting elements not at the end requires shifting subsequent elements, which is time-consuming.

Example:

#include <vector>
#include <iostream>

int main() {
    std::vector<int> v = {1, 2, 3};
    v.push_back(4); // may cause reallocation
    for (int x : v) {
        std::cout << x << " ";
    }
}