C++
Summary - Iterators
Combine begin/end and arithmetic to write a search function.
Summary - Iterators
In this group you learned what iterators are, the begin/end range, the five categories, range-based for and arithmetic. Now we combine these to write a search function.
Search starts with std::find: auto it = std::find(v.begin(), v.end(), 30);. To convert the found iterator to an index use std::distance(v.begin(), it). If the element is not found the iterator equals v.end(); we distinguish this case with if (it != v.end()).
Exercise Find and print the index
For v = {10, 20, 30, 40}, search for 30 with std::find. Compute its index with std::distance(v.begin(), it) and print it with std::cout.
Show example solution
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> v = {10, 20, 30, 40};
auto it = std::find(v.begin(), v.end(), 30);
std::cout << std::distance(v.begin(), it);
return 0;
}
Exercise Add a found message
Take the previous step's std::find and std::distance calls. After the index, print "found" if it != v.end(), otherwise "missing". Put the index and the message on separate lines.
Show example solution
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> v = {10, 20, 30, 40};
auto it = std::find(v.begin(), v.end(), 30);
std::cout << std::distance(v.begin(), it);
if (it != v.end()) {
std::cout << "\nfound";
} else {
std::cout << "\nmissing";
}
return 0;
}
Iterators recap
Iterators are the foundation of the STL. The begin/end half-open range is shared by all containers and algorithms. The five categories (input, output, forward, bidirectional, random access) are set by the container type.
Range-based for uses iterators behind the scenes. Random access iterators support +n, -n and []. With std::find and std::distance you can search and find indices. In the next group you will study STL algorithms in detail.
Test yourself
-
What converts an iterator to an index?
auto it = std::find(v.begin(), v.end(), 30);
- std::count
- std::distance
- std::sort
- std::copy
Show answer
std::distance — std::distance(begin, it) gives the index.
-
Complete the std::find call
auto it = std::____(v.begin(), v.end(), 30);
Show answer
auto it = std::find(v.begin(), v.end(), 30);
Next lesson: Model design