1. Goals
Store a growing list without managing its memory yourself.
Distinguish existing elements from reserved storage.
Check element access and recognize when references can become invalid.
2. Prerequisites
You know std::string, loops, const references, value copies, and RAII.
This lesson replaces the fixed arrays from stage 2 with std::vector.
You do not need to write templates to use std::vector<std::string>.
3. Explanation
A std::string owns a string; a std::vector<std::string> owns a sequence
of strings. The part inside <...> selects the element type. Destroying
the vector destroys its strings and releases its storage. Do not call delete.
push_back appends an element. size() counts existing elements;
empty() tells you whether there are none. When size() == 3, valid
indices are 0, 1, and 2. Use std::size_t for non-negative indices;
reject a negative user-provided signed integer before converting it.
titles.at(index) checks the bound and throws std::out_of_range when
index >= size(). In C++17, titles[index] does not provide a required
bounds check: you must establish that the index is valid before using it.
front() and back() also require a nonempty vector. The example uses
at and catches the exception to demonstrate a safe failure path.
renameTitle checks the index and the empty replacement before making
a change. A rejected call returns false and leaves the list unchanged.
This lesson accepts a string containing only spaces; empty() does
not trim whitespace.
for (const std::string& title : titles) reads each string without copying
it on every iteration. Remove const when you need to modify a string
through the reference. Do not add or erase elements of this vector inside
that loop: its traversal state can become invalid.
capacity() is the number of elements the vector can hold before
reallocating. reserve(3) prepares room for at least 3 elements;
it does not create three elements. An empty vector remains empty.
Use resize(3) if you actually want three empty strings. Do not assume
capacity exactly matches the request or always doubles.
The capacity and reserve rules
specify useful guarantees without prescribing one growth strategy.
When appending reallocates the vector, all pointers, references, and
iterators to existing elements become invalid. The old address or a
program that appears to work does not prove otherwise. Even without
reallocation, push_back invalidates the old end() iterator.
The vector modifier rules
describe that distinction; the next lesson introduces iterators.
The example saves firstIndex and an independent firstCopy before
appending. Afterwards, it accesses the element again through
at(firstIndex). Appending preserves existing indices, but inserting
or erasing in the middle can change positions: an index is not a
permanent book identity. Here, reserve(3) already covers all three
appends, so no further reallocation is needed.
std::string::size() counts char elements. For UTF-8 data, this counts
encoded bytes, not necessarily the characters a reader sees. Do not
truncate a Vietnamese title at an arbitrary byte position. The example
uses ASCII titles to make its output easy to compare.
After Foundation, continue with container selection and element construction in the C++11 sequence containers lesson.
4. Runnable example
Compile as C++17. The program reads no input and creates no files.
#include <cstddef>
#include <iostream>
#include <stdexcept>
#include <string>
#include <vector>
bool renameTitle(std::vector<std::string>& titles, std::size_t index,
const std::string& replacement) {
if (index >= titles.size() || replacement.empty()) {
return false;
}
titles.at(index) = replacement;
return true;
}
int main() {
std::vector<std::string> titles;
titles.reserve(3);
std::cout << std::boolalpha;
std::cout << "Empty after reserve: " << titles.empty() << '\n';
titles.push_back("Pointers");
titles.push_back("Lifetime");
const std::size_t firstIndex = 0;
const std::string firstCopy = titles.at(firstIndex);
titles.push_back("RAII");
std::cout << "Renamed: " << renameTitle(titles, firstIndex, "References") << '\n';
std::cout << "Saved copy: " << firstCopy << '\n';
std::cout << "Current first: " << titles.at(firstIndex) << '\n';
std::cout << "Count: " << titles.size() << '\n';
for (const std::string& title : titles) {
std::cout << "- " << title << '\n';
}
std::cout << "Bad index accepted: " << renameTitle(titles, titles.size(), "Other") << '\n';
std::cout << "Empty title accepted: " << renameTitle(titles, 0, "") << '\n';
try {
static_cast<void>(titles.at(titles.size()));
} catch (const std::out_of_range&) {
std::cout << "Out-of-range access rejected\n";
}
return 0;
}Output:
Empty after reserve: true
Renamed: true
Saved copy: Pointers
Current first: References
Count: 3
- References
- Lifetime
- RAII
Bad index accepted: false
Empty title accepted: false
Out-of-range access rejected5. Common mistakes
Accessing
titles[0]afterreserve(3)whilesize()is still0.Using
<= size()as an access condition;size()is already out of bounds.Keeping a
const std::string&to an element and using it after reallocation.Expecting the independent
firstCopyto follow changes to the original.Counting visible Vietnamese characters using the string's
size().Manually releasing storage owned by the vector.
6. Practice
Create an empty vector, call
reserve(10), and printsize()andempty(): they must be0andtrue. Append two titles and verifysize() == 2. Do not require one exact capacity value.For two titles, rename index
1successfully. Try indices2and100, and an empty replacement: all must returnfalsewithout changing either title. Also test index0on an empty vector.Copy the whole vector, rename an element in the copy, and print both. The original must retain its title. Then append many elements to the original and retrieve elements by index only after appending finishes.
Replace a title with Vietnamese text and compare
size()with the characters you see. Explain why a byte loop should not truncate the title.
7. Self-check
Does
reserve(20)makeat(0)valid on an empty vector? Answer: no. Reserve prepares storage while size remains0.at(0)throwsout_of_rangeuntil an element exists at that index.Why does
firstCopyremainPointersafter renaming the first title? Answer: it owns an independent copy of the string data. It is not a reference to the vector element.Is keeping a reference to the first title always safe across an append? Answer: no. Reallocation invalidates the reference. Retrieve the element again after the operation using an index that still identifies it; do not use the old reference to test whether it is valid.
Sample code
Source file
cpp98_foundation/20_strings_vectors/main.cpp
#include <cstddef>
#include <iostream>
#include <stdexcept>
#include <string>
#include <vector>
bool renameTitle(std::vector<std::string>& titles, std::size_t index,
const std::string& replacement) {
if (index >= titles.size() || replacement.empty()) {
return false;
}
titles.at(index) = replacement;
return true;
}
int main() {
std::vector<std::string> titles;
titles.reserve(3);
std::cout << std::boolalpha;
std::cout << "Empty after reserve: " << titles.empty() << '\n';
titles.push_back("Pointers");
titles.push_back("Lifetime");
const std::size_t firstIndex = 0;
const std::string firstCopy = titles.at(firstIndex);
titles.push_back("RAII");
std::cout << "Renamed: " << renameTitle(titles, firstIndex, "References") << '\n';
std::cout << "Saved copy: " << firstCopy << '\n';
std::cout << "Current first: " << titles.at(firstIndex) << '\n';
std::cout << "Count: " << titles.size() << '\n';
for (const std::string& title : titles) {
std::cout << "- " << title << '\n';
}
std::cout << "Bad index accepted: " << renameTitle(titles, titles.size(), "Other") << '\n';
std::cout << "Empty title accepted: " << renameTitle(titles, 0, "") << '\n';
try {
static_cast<void>(titles.at(titles.size()));
} catch (const std::out_of_range&) {
std::cout << "Out-of-range access rejected\n";
}
return 0;
}