C++ Vectors

A vector is like an array that can grow and shrink while your program runs. You do not have to decide the size ahead of time, and you can add or remove elements whenever you need. Vectors live in the <vector> library and are one of the most useful tools in modern C++.

Creating a vector

Include the <vector> header, then declare a vector by naming the type of data it will hold inside angle brackets. You can start it empty or fill it with values right away using curly braces.

Declare and print a vector

#include <iostream>
#include <vector>
#include <string>
using namespace std;

int main() {
  vector<string> fruits = {"apple", "banana", "cherry"};

  cout << fruits[0] << "\n";
  cout << fruits[1] << "\n";
  cout << fruits[2] << "\n";
  return 0;
}

Adding and removing elements

Use push_back() to add an element to the end of a vector, and pop_back() to remove the last element. This ability to change size while running is what makes vectors more flexible than plain arrays.

Grow and shrink a vector

#include <iostream>
#include <vector>
#include <string>
using namespace std;

int main() {
  vector<string> colors;
  colors.push_back("red");
  colors.push_back("green");
  colors.push_back("blue");

  colors.pop_back(); // removes "blue"

  cout << "There are " << colors.size() << " colors left.";
  return 0;
}

Common vector functions

Vectors come with helpful built-in functions. Here are the ones you will reach for most often as a beginner.

FunctionDescription
push_back(x)Adds element x to the end
pop_back()Removes the last element
size()Returns how many elements there are
at(i)Safely returns the element at index i
clear()Removes all elements

Looping through a vector

The cleanest way to visit every element is a range-based for loop. It reads each element one by one without you needing to manage index numbers. Using the & symbol with auto avoids copying each element.

Loop over every element

#include <iostream>
#include <vector>
using namespace std;

int main() {
  vector<int> scores = {90, 75, 88, 100};
  int total = 0;

  for (const auto& score : scores) {
    total += score;
  }

  cout << "Total score: " << total;
  return 0;
}
Note: Use at(i) instead of [i] when you want safety. If the index is out of range, at() throws an exception you can catch, while [i] simply reads invalid memory and causes hard-to-find bugs.
  • A vector can grow and shrink while the program runs.
  • Include <vector> and declare the element type in angle brackets.
  • Add with push_back() and remove with pop_back().
  • Use size() to count elements and a range-based for loop to visit them.

Exercise: C++ Vectors

How does the size of a std::vector compare to a raw C++ array once it's created?