๐ŸŽ“ A1Learner
๐Ÿ”

C++ Vectors

A vector is a list of values of one type that can grow while a program runs. A program includes the vector header to use the std::vector type.

Printing a vector with a loop

A vector cannot be printed whole, so the loop prints one element at a time. The size method sets how far the counter runs.

#include <iostream>
#include <vector>

int main() {
  std::vector<int> scores = {85, 90, 78};
  for (int i = 0; i < scores.size(); i++) {
    std::cout << scores[i] << std::endl;
  }
  return 0;
}

Growing a vector

The first print shows the size before push_back runs. The second print shows the size after one element is added.

#include <iostream>
#include <vector>

int main() {
  std::vector<int> scores = {85, 90};
  std::cout << scores.size() << std::endl;
  scores.push_back(78);
  std::cout << scores.size() << std::endl;
  return 0;
}

Reading with at

The at method takes an index. Index 1 reads the second element.

#include <iostream>
#include <vector>

int main() {
  std::vector<int> scores = {85, 90, 78};
  std::cout << scores.at(1) << std::endl;
  return 0;
}

Printing with a range-for

The range-for takes each element in order. Each element prints on its own line.

#include <iostream>
#include <vector>

int main() {
  std::vector<int> scores = {85, 90, 78};
  for (int score : scores) {
    std::cout << score << std::endl;
  }
  return 0;
}

Example

#include <iostream>
#include <vector>

int main() {
  std::vector<int> scores = {70, 80, 90};
  scores.push_back(100);
  for (int score : scores) {
    std::cout << score << std::endl;
  }
  std::cout << "Size: " << scores.size() << std::endl;
  return 0;
}

Key points

  • The std::vector type comes from the vector header.
  • A vector stores values of one type.
  • Calling size() gives the number of elements a vector holds.
  • The push_back method adds one element at the end.
  • The at method reads the element at a given index.
  • Index brackets also read an element at an index.

In this example, the vector starts with three scores. push_back adds 100 at the end. The loop prints all four scores, and the last line prints the size as 4.

Note

A vector starts with the elements given at declaration, and push_back can add more later.

Try it Yourself

Edit the code, then press Run.

Running is simulated ยท Programiz C++ Compiler

Exercise

What does push_back do?