Um momento
0x40Lesson 5 of 9

Work with strings and vectors

Use standard containers to manage text and growable sequences safely.

16 min 5-question quiz 1 code exercise
By the end of this lesson you can
  • Use std::string, std::vector, and range-based for loops.

std::vector<T> stores a sequence of values that can grow or shrink, and std::string stores text. Include <vector> and <string> for these types. A range-based loop visits each element directly. Use const auto& when you only need to inspect possibly large elements without copying. Indexing starts at zero; at() checks bounds and throws an exception if the index is invalid.

main.cpp · C++20
1#include <iostream>
2#include <vector>
3
4int main() {
5    const std::vector<int> scores{8, 5, 9};
6    for (const auto& score : scores) {
7        std::cout << score << "\n";
8    }
9}
Output
8
5
9

auto asks the compiler to infer a type from the initializer. Here const auto& means a read-only reference to each vector element. Standard containers manage their own storage and clean it up automatically when they leave scope.

Key takeaways

  • Prefer standard containers to manually managed arrays for everyday sequences.

  • Use range loops to express element-wise processing.

  • Containers clean up their resources automatically.

Lesson quiz

5 questions · pass with 4 correct · up to 50 XP

Passing this quiz completes the lesson and keeps your streak going. Questions you miss come back in review sessions later.

Practice: write C++

Write C++20 in the editor and run it against sample input. GCC 14 compiles the code through Compiler Explorer, a free public service; your source and test input are sent there.

Exercise 1

Sum a vector of numbers

+25 XP

Read a count followed by that many integers. Store them in a vector and print Total: N.

  • Three values
  • Empty vector
main.c
Loading editor…

Your code is compiled as C++20 with gcc 14 (-Wall -Wextra) and run on Compiler Explorer (godbolt.org), a free public service.

Questions about this lesson

Stuck? Ask. Figured something out? Share it. Explaining is one of the best ways to learn.

Loading posts…

Gostou da aula? 😆👍
Apoie nosso trabalho com uma doação: