Intermediate level · Module 3: The Standard Template Library · Lesson 2 of 3
Iterators and Algorithms
Use iterators to connect containers to the standard algorithms for counting, searching, transforming and removing.
In this lesson you will
- Use begin/end iterators with standard algorithms
- Apply count_if, find_if, transform and erase_if
Key concepts
iteratorfind_if / count_ifstd::transformstd::erase_if
The lesson
Iterators are generalised positions in a container. begin() points at the first element and end() just past the last. Algorithms take a pair of iterators, so the same std::count_if works on a vector, a list or a set.
std::find_if returns an iterator to the first element matching a condition, or end() when none matches — always compare with end() before using the result. std::transform applies a function to each element and writes the results to another range.
Removing elements is a common trap: std::remove_if only moves the kept elements to the front. Use C++20's std::erase_if(vec, condition) to actually remove them, or the older erase–remove idiom.
Step by step
- Count products over a price limit with count_if.
- Find the first out-of-stock product with find_if and check against end().
- Convert prices from SSP to USD with transform.
- Remove discontinued products with std::erase_if.
Counting requests with std::map
Count how often each item appears in a list of requests and print the counts in alphabetical order.
#include <iostream>#include <map>#include <sstream>#include <string> int main() { std::string text = "water food water shelter food water"; std::map<std::string, int> counts; std::istringstream words(text); std::string word; while (words >> word) { ++counts[word]; } for (const auto& [item, count] : counts) { std::cout << item << ": " << count << '\n'; }}
Output
food: 2
shelter: 1
water: 3How it works
std::istringstream lets >> read the text one word at a time. counts[word] creates a zero count the first time a word is seen, and ++ increases it. std::map keeps its keys sorted, so the loop prints the items alphabetically; the structured binding [item, count] unpacks each key–value pair. An NGO could use the same pattern to tally requests from a needs assessment.
Key concepts
std::mapoperator[] inserting defaultsstd::istringstreamstructured bindings
Practice activity
Implement the market-price queries from the practical activity using only algorithms, no hand-written loops for counting or searching.
Expected result: Each query gives the expected result, and the code uses standard algorithms throughout.
Check your understanding
-
What does find_if return when nothing matches?
Show answer
The end iterator.
-
Does std::remove_if shrink the container?
Show answer
No; use erase or std::erase_if to actually remove the elements.
Taught live by an instructor — online or in person. Free course lessons are for self-study and do not lead to a certificate — see registration options.