Find items in a container
The algorithm
library contains a set of functions for finding elements in a container. The std::find()
function, and its derivatives, search sequentially through a container and return an iterator pointing to the first matching element, or the end()
element if there's no match.
How to do it…
The find()
algorithm works with any container that satisfies the Forward or Input iterator qualifications. For this recipe, we'll use vector
containers. The find()
algorithm searches sequentially for the first matching element in a container. In this recipe, we'll walk through a few examples:
- We'll start by declaring a
vector
ofint
in themain()
function:int main() { const vector<int> v{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 }; ... }
- Now, let's search for the element with the value
7
:auto it1 = find(v.begin(), v.end(), 7); if(it1 != v.end()) cout << format("found...