What is a Vector

beginner c++17 containers vector

Related: How to Add to Vector

A vector in C++ is a contiguous array that can grow and shrink in size. Contiguous means the elements in the vector are stored next to each other in memory. This makes accessing the elements in order, also known as iteration, very efficient for vector. Vector is provided by the standard library in the <vector> header and is called std::vector.

#include <vector>
#include <iostream>

int main() {
  std::vector<int> vec{1, 2, 3};
  vec.push_back(4);

  std::cout << "vec.size(): " << vec.size() << "\n";
  std::cout << "vec[1]: " << vec[1] << "\n";

  vec.pop_back();
  for (auto n : vec) {
    std::cout << n << "\n";  
  }
}
vec.size(): 4
vec[1]: 2
1
2
3


For more C++ By Example, click here.