Work with strings and vectors
Use standard containers to manage text and growable sequences safely.
- Use
std::string,std::vector, and range-basedforloops.
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.
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}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.
Sum a vector of numbers
Read a count followed by that many integers. Store them in a vector and print Total: N.
- Three values
- Empty vector
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…