1. Goals
Read a
[begin, end)range and handle a search that finds nothing.Use
std::find,std::sort, and a simple comparison function.Erase while iterating without reusing invalid iterators.
2. Prerequisites
You know that vectors own elements, how indices work, what a const
reference means, and that reallocation can invalidate aliases. You can
write a function returning bool. This lesson passes such functions
to standard library algorithms.
3. Explanation
An iterator represents a position in a sequence. For a vector,
begin() points to the first element when one exists; end() denotes
the position just past the last element. The range [begin, end)
includes its beginning and excludes its end. An empty vector has
begin() == end(). Never dereference end(), empty vector or otherwise.
*current accesses the element at that position; ++current moves
one step forward. Only increment an iterator before the end, and
dereference it only after checking it differs from end(). Both range
endpoints must belong to the same sequence and be in the correct order.
Here, auto asks the compiler to deduce the iterator type from its
initializer; it does not remove types or type checking.
cbegin() and cend() provide iterators that cannot modify elements
through the iterator. containsTitle accepts a const vector
reference because it only checks for membership.
std::find(first, last, target) returns the first matching iterator or
last if nothing matches. Compare with the end before using *result.
The input need not be sorted. For N elements, it performs at most
N equality comparisons: a linear search. The
find specification covers the
missing-element result and comparison bound.
std::sort rearranges the vector in place. Vector iterators support
this algorithm; not every container does. titleBefore(left, right)
returns left < right, meaning the left title should precede the right.
Pass the function name to sort; the algorithm calls that function
with pairs of elements.
The comparison must be consistent: a value must not precede itself;
if A precedes B and B precedes C, A must precede C. Using <= instead
of < breaks the first condition for equal titles. The standard
requires a strict weak ordering; the string comparison here meets
that requirement. Equal titles remain in the result. sort neither
removes duplicates nor guarantees the original order of equivalent
elements. The sorting requirements
describe the comparator contract.
This string comparison is case-sensitive and follows code-unit order,
not Vietnamese name collation. sort uses O(N log N) comparisons;
that is not a duration, and comparing long strings has its own cost.
Sorting before every find does not turn find into binary search.
The sort specification gives the
comparison bound.
eraseTitle removes every match. It copies target into value
before changing the vector: a caller can pass titles.at(0) itself,
and erasing that element will not leave the search value dangling.
erase(current) invalidates iterators at and after the erased position,
then returns a fresh iterator to the next element, or end().
Assign that result to current; increment only when nothing was erased.
The loop obtains end() again after each operation. Erasing the final
element returns the new end, stopping the loop. This handles empty
lists, missing titles, and consecutive duplicates. However, erasing
inside a vector shifts elements: repeated erasures can require
O(N²) element shifts. Later lessons cover compacting elements before
one erase; understand correctness before optimizing this example.
After Foundation, continue with iterator categories and invalidation and algorithms, numeric algorithms, and lambdas.
4. Runnable example
Compile as C++17. ASCII titles make the output order easy to inspect.
#include <algorithm>
#include <cstddef>
#include <iostream>
#include <string>
#include <vector>
bool titleBefore(const std::string& left, const std::string& right) {
return left < right;
}
bool containsTitle(const std::vector<std::string>& titles,
const std::string& target) {
return std::find(titles.cbegin(), titles.cend(), target) != titles.cend();
}
std::size_t eraseTitle(std::vector<std::string>& titles,
const std::string& target) {
const std::string value = target;
std::size_t removed = 0;
auto current = titles.begin();
while (current != titles.end()) {
if (*current == value) {
current = titles.erase(current);
++removed;
} else {
++current;
}
}
return removed;
}
int main() {
std::vector<std::string> titles{"RAII", "Pointers", "RAII", "Classes"};
std::cout << std::boolalpha;
std::cout << "Found RAII: " << containsTitle(titles, "RAII") << '\n';
std::cout << "Found Missing: " << containsTitle(titles, "Missing") << '\n';
std::sort(titles.begin(), titles.end(), titleBefore);
std::cout << "Sorted:\n";
for (auto current = titles.cbegin(); current != titles.cend(); ++current) {
std::cout << "- " << *current << '\n';
}
std::cout << "Removed RAII: " << eraseTitle(titles, "RAII") << '\n';
std::cout << "Remaining: " << titles.size() << '\n';
const std::vector<std::string> empty;
std::cout << "Found in empty: " << containsTitle(empty, "RAII") << '\n';
std::vector<std::string> allSame{"RAII", "RAII"};
std::cout << "Removed all: " << eraseTitle(allSame, allSame.at(0)) << '\n';
std::cout << "Empty after erase: " << allSame.empty() << '\n';
return 0;
}Output:
Found RAII: true
Found Missing: false
Sorted:
- Classes
- Pointers
- RAII
- RAII
Removed RAII: 2
Remaining: 2
Found in empty: false
Removed all: 2
Empty after erase: true5. Common mistakes
Dereferencing
std::find(...)without checking for the end.Combining one vector's
begin()with another vector'send().Using
<=in the comparator or modifying elements from the comparator.Incrementing the old iterator after
erase, or skipping an element by incrementing the newly returned iterator immediately.Reusing an old
end()or a reference to an erased element.Expecting sort to remove duplicates or preserve equivalent elements' order.
6. Practice
Test
containsTitlewith an empty list, an existing title, and a missing title: expectfalse,true, andfalse. Callfinddirectly and print its result only when the iterator is not the end.Sort
{"B", "A", "B"}into{"A", "B", "B"}. Also try an empty list and a one-element list. Write a descending comparator with>, not>=.Remove
"B"from{"B", "B", "A", "B"}: expect3removals and only"A"remaining. Removing it again must return0. Removing from an empty vector must also return0.For
{"A", "A", "B"}, calleraseTitle(titles, titles.at(0)): expect two removals and only"B"remaining. Explain whyvaluemust be copied before the first erase.
7. Self-check
Does an unsuccessful find return the last element? Answer: no. It returns the end position after the last element, where there is nothing to read. An empty list also returns the end.
Why not call
++currentin the erase branch? Answer: erase already returns the next position to examine. Incrementing again skips that element; incrementing the end is invalid.Why can searching a sorted vector still take
Ncomparisons? Answer:std::findremains a linear traversal. Exploiting sorted order requires a search algorithm for sorted ranges and a matching comparator.
Sample code
Source file
cpp98_foundation/21_iterators_algorithms/main.cpp
#include <algorithm>
#include <cstddef>
#include <iostream>
#include <string>
#include <vector>
bool titleBefore(const std::string& left, const std::string& right) {
return left < right;
}
bool containsTitle(const std::vector<std::string>& titles,
const std::string& target) {
return std::find(titles.cbegin(), titles.cend(), target) != titles.cend();
}
std::size_t eraseTitle(std::vector<std::string>& titles,
const std::string& target) {
const std::string value = target;
std::size_t removed = 0;
auto current = titles.begin();
while (current != titles.end()) {
if (*current == value) {
current = titles.erase(current);
++removed;
} else {
++current;
}
}
return removed;
}
int main() {
std::vector<std::string> titles{"RAII", "Pointers", "RAII", "Classes"};
std::cout << std::boolalpha;
std::cout << "Found RAII: " << containsTitle(titles, "RAII") << '\n';
std::cout << "Found Missing: " << containsTitle(titles, "Missing") << '\n';
std::sort(titles.begin(), titles.end(), titleBefore);
std::cout << "Sorted:\n";
for (auto current = titles.cbegin(); current != titles.cend(); ++current) {
std::cout << "- " << *current << '\n';
}
std::cout << "Removed RAII: " << eraseTitle(titles, "RAII") << '\n';
std::cout << "Remaining: " << titles.size() << '\n';
const std::vector<std::string> empty;
std::cout << "Found in empty: " << containsTitle(empty, "RAII") << '\n';
std::vector<std::string> allSame{"RAII", "RAII"};
std::cout << "Removed all: " << eraseTitle(allSame, allSame.at(0)) << '\n';
std::cout << "Empty after erase: " << allSame.empty() << '\n';
return 0;
}