Strings and Vectors
Strings and Vectors
Work with dynamic text and lists using the most common standard library types.
Strings and Vectors
Work with dynamic text and lists using the most common standard library types.
std::stringstd::string text = "hello";
text += " world";
std::vectorstd::vector<int> scores{10, 20, 30};
scores.push_back(40);
for (const auto& score : scores) {
std::cout << score << '\n';
}
#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';
}
std::vector over manual dynamic arraysconst&std::vector<std::string> names;
names.reserve(100);
Reserve capacity when you know approximate growth. It reduces reallocations and iterator invalidation.
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.
Once vectors and strings feel comfortable, start replacing manual loops with algorithms such as std::ranges::sort, std::ranges::find, and std::ranges::transform.