OSC++.012: Vector Methods

Black and neon-green C++ lesson cover showing vector push_back, pop_back, size, and empty methods

A C++ vector is a container that can hold multiple values. In OSC++.010, we introduced vectors. In OSC++.011, we looped through them. Now we will learn four simple vector methods that let us add, remove, count, and check items.

Start With a Vector

#include <iostream>
#include <vector>

int main() {
    std::vector<int> scores = {21, 34, 55};
}

Our vector is named scores. It currently contains three numbers.

push_back(): Add an Item

scores.push_back(89);

push_back() adds a new item to the end of the vector. The vector is now {21, 34, 55, 89}.

Video: C++ Vector Methods

This beginner C++ vector walkthrough demonstrates common vector operations including push_back(), pop_back(), and size().

pop_back(): Remove the Last Item

scores.pop_back();

pop_back() removes the last item. If the last value was 89, the vector returns to {21, 34, 55}. Only call it when the vector is not empty.

size(): Count the Items

std::cout << scores.size();

size() returns the number of elements in the vector. For {21, 34, 55}, the result is 3.

empty(): Is Anything There?

if (scores.empty()) {
    std::cout << "No scores yet";
}

empty() returns true when the vector has no elements and false when it contains at least one element.

Gaming Example

std::vector<int> lapTimes;
lapTimes.push_back(72);
lapTimes.push_back(68);

std::cout << "Laps: " << lapTimes.size();

A racing game could add each completed lap time to a vector and use size() to count how many laps have been recorded.

Bitcoin Mining Example

std::vector<int> minerTemps;
minerTemps.push_back(61);
minerTemps.push_back(64);
minerTemps.push_back(63);

A simple monitoring program could store temperature readings from a Bitcoin mining machine in a vector as new readings arrive.

Practice

  1. Create a vector containing three numbers.
  2. Use push_back() to add a fourth number.
  3. Print the result of size().
  4. Use pop_back() once.
  5. Check the vector with empty().

Key Takeaway

push_back() adds an item, pop_back() removes the last item, size() counts the items, and empty() checks whether the vector contains anything. These four methods make vectors much more useful in everyday C++ programs.

Leave a comment