C++ What is a vector?

‮w‬ww.theitroad.com

In C++, vector is a standard template library (STL) sequence container that provides dynamic array-like functionality. It is a dynamic container, meaning that it can change size during runtime, and it can store elements of any type.

A vector container can be declared as follows:

#include <vector>
std::vector<int> myVector; // a vector of integers

Here, std::vector is a templated class that takes one template parameter: the type of the elements to store (int in this case).

The vector container provides several member functions, including:

  • push_back(): adds an element to the end of the vector.
  • pop_back(): removes the last element from the vector.
  • size(): returns the number of elements in the vector.
  • empty(): returns true if the vector is empty.
  • clear(): removes all elements from the vector.
  • resize(): changes the size of the vector.
  • reserve(): reserves memory for a specified number of elements.

vector containers are useful when the size of the data is not known at compile time and may change during runtime. They are also more efficient than dynamic arrays, since they automatically handle memory allocation and deallocation, and provide a range of functions to manipulate the data.

Here is an example of using the vector container:

#include <iostream>
#include <vector>

int main()
{
  std::vector<int> myVector;

  // Add elements to the vector
  myVector.push_back(1);
  myVector.push_back(2);
  myVector.push_back(3);

  // Output vector size
  std::cout << "Size of vector: " << myVector.size() << std::endl;

  // Remove last element from vector
  myVector.pop_back();

  // Output vector contents
  std::cout << "Contents of vector: ";
  for (int i = 0; i < myVector.size(); ++i)
    std::cout << myVector[i] << ' ';
  std::cout << std::endl;

  return 0;
}

Output:

Size of vector: 3
Contents of vector: 1 2