Strings and Vectors

Strings and Vectors

Work with dynamic text and lists using the most common standard library types.

Strings and Vectors

std::string

std::string text = "hello";
text += " world";

std::vector

std::vector<int> scores{10, 20, 30};
scores.push_back(40);

Iteration

for (const auto& score : scores) {
    std::cout << score << '\n';
}

Example: average calculator

#include <iostream>
#include <vector>

int main() {
    std::vector<int> values{4, 8, 15, 16, 23, 42};
    int sum = 0;

    for (int value : values) {
        sum += value;
    }

    std::cout << "Average: " << sum / values.size() << '\n';
}

Key lessons

Growth and capacity

std::vector<std::string> names;
names.reserve(100);

Reserve capacity when you know approximate growth. It reduces reallocations and iterator invalidation.

String views and ranges

std::string title = "Modern C++";
std::string_view view = title;

Use std::string_view for read-only access, but remember it does not own the string.

Next modern step

Once vectors and strings feel comfortable, start replacing manual loops with algorithms such as std::ranges::sort, std::ranges::find, and std::ranges::transform.