How to Use find in C++: Syntax, Example, and Tips
In C++, use
std::find from the <algorithm> header to search for an element in a container by providing the start and end iterators and the value to find. It returns an iterator to the found element or the end iterator if not found.Syntax
The std::find function has this syntax:
std::find(start_iterator, end_iterator, value_to_find)
Here, start_iterator and end_iterator define the range to search in, and value_to_find is the element you want to locate.
The function returns an iterator pointing to the first occurrence of the value or the end_iterator if the value is not found.
cpp
auto it = std::find(container.begin(), container.end(), value);
Example
This example shows how to find a number in a vector and check if it was found.
cpp
#include <iostream> #include <vector> #include <algorithm> // for std::find int main() { std::vector<int> numbers = {10, 20, 30, 40, 50}; int target = 30; auto it = std::find(numbers.begin(), numbers.end(), target); if (it != numbers.end()) { std::cout << "Found " << target << " at position " << (it - numbers.begin()) << "\n"; } else { std::cout << target << " not found in the vector.\n"; } return 0; }
Output
Found 30 at position 2
Common Pitfalls
Common mistakes when using std::find include:
- Not including the
<algorithm>header. - Forgetting to compare the returned iterator with the container's
end()iterator before using it. - Using
std::findon containers without iterators (like raw arrays without pointers).
Always check if the element was found before dereferencing the iterator.
cpp
#include <iostream> #include <vector> #include <algorithm> int main() { std::vector<int> v = {1, 2, 3}; int val = 4; // Wrong: dereferencing without check // auto it = std::find(v.begin(), v.end(), val); // std::cout << *it << '\n'; // Undefined behavior if not found // Right way: auto it = std::find(v.begin(), v.end(), val); if (it != v.end()) { std::cout << "Found: " << *it << '\n'; } else { std::cout << val << " not found." << '\n'; } return 0; }
Output
4 not found.
Quick Reference
Summary tips for using std::find:
- Include
<algorithm>to usestd::find. - Pass iterators defining the search range.
- Compare the result with
end()before using it. - Works with any container supporting iterators (vector, list, array, etc.).
Key Takeaways
Use std::find with start and end iterators plus the value to search.
Always check if the returned iterator equals end() before using it.
Include header to access std::find.
std::find works with any container that supports iterators.
Dereferencing the iterator without checking can cause errors if not found.