Vectors

Programming Languages · C++ Loops & Vectors · 10 min

Keep a list of values in a std::vector, grow it, and loop over it.

A list of values

A std::vector holds many values of one type, in order. Add #include <vector> at the top, then put the type in angle brackets:

std::vector<int> scores = {90, 75, 82};
std::cout << scores.size() << "\n";   // 3

.size() tells you how many values are inside.

  • Create a std::vector<int> called nums holding 4, 8, 15 and 16.

  • Print how many values it holds with nums.size().

Getting one value

Each value has a position called an index. Counting starts at 0, so the first value is [0]:

std::vector<std::string> pets = {"cat", "dog"};
std::cout << pets[0] << "\n";   // cat
pets[1] = "fish";                // replace dog
  • Print the first fruit using fruits[0].

  • Change fruits[1] to "blueberry", then print fruits[1].

Growing with push_back

Vectors can grow. push_back adds a value to the end:

std::vector<int> nums = {1, 2};
nums.push_back(3);   // now {1, 2, 3}
  • Add "Cleo" to the end of guests with push_back.

  • Print guests.size(), then on the next line print guests[2].

Visiting every value

To do something with every value, use a range-based for loop. Read it as "for each n in nums":

std::vector<int> nums = {10, 20};
for (int n : nums) {
    std::cout << n << "\n";
}

Each time round, n holds the next value.

  • Print every value in nums on its own line, using a range-based for loop.

Put it together: shopping cart

Your cart has three prices. Add one more item, count the items, and add up the bill with a loop and a running total.

  • Add 15 to prices with push_back.

  • Print Items: 4 using prices.size().

  • Add every price to total with a range-based for loop, then print Total: 40.

More in C++ Loops & Vectors

Previous: Loops · Next: Functions