STL Vector in C++

A vector in C++ is a dynamic array that can grow or shrink its size as needed. It is one of the most commonly used containers in the C++ Standard Template Library (STL).

A vector is a sequence container that encapsulates dynamic arrays. Vectors are similar to arrays, but they can grow and shrink their size as needed. This makes them more flexible than arrays, which have a fixed size.

Types

There are two types of vectors in C++

Sequential vectors

These vectors store their elements in a contiguous block of memory. This makes them faster to access than other types of vectors.

Linked vectors

These vectors store their elements in a linked list. This makes them slower to access than sequential vectors, but it also makes them more flexible.

Syntax
std::vector<T> vector_name;
Example
#include<vector>
int main() {
  // Create a vector of integers.
  std::vector v;
  // Add some elements to the vector.
  v.push_back(1);
  v.push_back(2);
  // Print the elements of the vector.
  for (int i = 0; i < v.size(); i++) {
    std::cout << v[i] << std::endl;
  }
  // Return 0 to indicate success.
  return 0;
}

This code will print the following output:

1
2
Operations

Vectors support a variety of operations, including:

std::vector::push_back(): Appends an element to the end of the vector.

Example
std::vector<int>numbers;
numbers.push_back(1);     // {1}
numbers.push_back(2);     // {1, 2}
numbers.push_back(3);     // {1, 2, 3}

std::vector::pop_back(): Removes the last element from the vector.

Example
std::vector<int> numbers = {1, 2, 3};
numbers.pop_back();       // {1, 2}

std::vector::size(): Returns the number of elements in the vector.

Example
std::vector<int>numbers = {1, 2, 3};
int size = numbers.size(); // 3

std::vector::empty(): Checks if the vector is empty.

Example
std::vector<int>numbers;
bool isEmpty = numbers.empty(); // true

std::vector::clear(): Removes all elements from the vector.

Example
std::vector<int>numbers = {1, 2, 3};
numbers.clear();           // {}

std::vector::insert(): Inserts an element at a specified position in the vector.

Example
std::vector<int>numbers = {1, 2, 3};
auto it = numbers.begin() + 1;
numbers.insert(it, 4);     // {1, 4, 2, 3}

std::vector::erase(): Removes an element at a specified position in the vector.

Example
std::vector<int>numbers = {1, 2, 3};
auto it = numbers.begin() + 1;
numbers.erase(it);         // {1, 3}

std::vector::resize(): Resizes the vector to a specified size, potentially adding or removing elements.

Example
std::vector<int>numbers = {1, 2, 3};
numbers.resize(5);         // {1, 2, 3, 0, 0}