CodeBlanks Logo Icon CodeBlanks

std::find

Learn to search with std::find.

std::find

std::find searches for a value in a range. With auto it = std::find(v.begin(), v.end(), 20); you search for the value 20. If found it returns an iterator to that element, otherwise it returns v.end().

The search is linear (O(n)): it checks each element from start to end. If the value is not found it == v.end(). That is why you check the result with if (it != v.end()). std::find works with every iterator category: std::vector, std::list and even raw pointers.

Checking the result

std::find returns an iterator. If the value was found the iterator points at a valid element; if not it equals v.end(). That is why we distinguish the cases with if (it != v.end()).

You read the found value with *it. You compute its index with std::distance(v.begin(), it). These two approaches are the standard way to turn an iterator into a value or an index. If the search fails *it is not used; because end() is never dereferenced.

Practice Search a value and print a message

For v = {10, 20, 30}, search for 20 with std::find. Print "found" if found, "missing" otherwise. Check the condition with it != v.end().

Starter code

main.cpp
#include <iostream>
#include <vector>
#include <algorithm>

int main() {
    std::vector<int> v = {10, 20, 30};
    // Search 20 with std::find, print the result
    return 0;
}

Sample solution

main.cpp
#include <iostream>
#include <vector>
#include <algorithm>

int main() {
    std::vector<int> v = {10, 20, 30};
    auto it = std::find(v.begin(), v.end(), 20);
    if (it != v.end()) {
        std::cout << "found";
    } else {
        std::cout << "missing";
    }
    return 0;
}

Expected output

found

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Complete the find call

Question
auto it = std::____(v.begin(), v.end(), 20);
Answer
auto it = std::find(v.begin(), v.end(), 20);

Explanation: std::find searches for a value.

2 What does std::find return when the element is not found?

main.cpp
auto it = std::find(v.begin(), v.end(), 99);
  • the v.end() iterator Correct answer
  • 0
  • -1
  • nullptr

Explanation: When not found it returns the end() iterator.

3 Match each expression to its meaning

Term Meaning
std::find(begin, end, v) Value search
it != v.end() Found condition
*it Found element
std::distance(begin, it) Index computation

All lessons in Intermediate