C++ <algorithm> std::find

The std::find function template in C++ is part of the <algorithm> header and is used to search for the first occurrence of a specified value within a range defined by two iterators. If the value is found, it returns an iterator pointing to the first occurrence; otherwise, it returns the end iterator.


Syntax of std::find

</>
Copy
template <class InputIterator, class T>
InputIterator find(InputIterator first, InputIterator last, const T& val);

Parameters of std::find

ParameterDescription
firstAn input iterator to the initial position in a sequence.
lastAn input iterator to the final position in a sequence (one past the last element).
valThe value to search for in the range.

Return Value of std::find

An iterator to the first element in the range that compares equal to val. If no such element is found, the function returns last.


Exceptions for std::find

Throws if any of the element comparisons or operations on the iterators throw exceptions. Note that invalid parameters cause undefined behavior.


Examples for algorithm find function

Example 1: Using std::find with an Array

In this example, we use std::find to search for a value in an array.

Program

</>
Copy
#include <iostream>
#include <algorithm> // For std::find

int main() {
    int myints[] = {10, 20, 30, 40};
    int* p;

    p = std::find(myints, myints + 4, 30);
    if (p != myints + 4)
        std::cout << "Element found in myints: " << *p << '\n';
    else
        std::cout << "Element not found in myints\n";

    return 0;
}

Output

Element found in myints: 30

Explanation

  1. We include the necessary headers: <iostream> for input/output operations and <algorithm> for the std::find function.
  2. An array myints is initialized with the values {10, 20, 30, 40}.
  3. We use std::find to search for the value 30 in the array. The function searches in the range [myints, myints + 4).
  4. If the value is found, p points to the element, and we print its value. Otherwise, we print that the element was not found.

Example 2: Using std::find with a Vector

This example demonstrates how to use std::find to search for a value in a std::vector.

Program

</>
Copy
#include <iostream>
#include <vector>
#include <algorithm> // For std::find

int main() {
    std::vector<int> myvector = {10, 20, 30, 40};
    auto it = std::find(myvector.begin(), myvector.end(), 30);

    if (it != myvector.end())
        std::cout << "Element found in myvector: " << *it << '\n';
    else
        std::cout << "Element not found in myvector\n";

    return 0;
}

Output

Element found in myvector: 30

Explanation

  1. We include the necessary headers: <iostream> for input/output operations, <vector> for the std::vector container, and <algorithm> for the std::find function.
  2. A vector myvector is initialized with the values {10, 20, 30, 40}.
  3. We use std::find to search for the value 30 in the vector. The function searches in the range [myvector.begin(), myvector.end()).
  4. If the value is found, it points to the element, and we print its value. Otherwise, we print that the element was not found.

Example 3: Using std::find with a List

In this example, we use std::find to search for a value in a std::list.

Program

</>
Copy
#include <iostream>
#include <list>
#include <algorithm> // For std::find

int main() {
    std::list<int> mylist = {10, 20, 30, 40};
    auto it = std::find(mylist.begin(), mylist.end(), 25);

    if (it != mylist.end())
        std::cout << "Element found in mylist: " << *it << '\n';
    else
        std::cout << "Element not found in mylist\n";

    return 0;
}

Output

Element not found in mylist

Explanation

  1. We include the necessary headers: <iostream> for input/output operations, <list> for the std::list container, and <algorithm> for the std::find function.
  2. A list mylist is initialized with the values {10, 20, 30, 40}.
  3. We use std::find to search for the value 25 in the list. The function searches in the range [mylist.begin(), mylist.end()).
  4. Since the value 25 is not present in the list, it is equal to mylist.end().
  5. The program prints “Element not found in mylist” because the value was not found.

Examples for Exceptions Thrown by find function

The std::find function can throw exceptions in two primary scenarios:

  • If the comparison between the elements throws an exception.
  • If an operation on the iterators (such as dereferencing or incrementing) throws an exception.

Example 1: Exception Thrown by Element Comparison

This example demonstrates a case where the comparison operation throws an exception during execution.

Program

</>
Copy
#include <iostream>
#include <vector>
#include <algorithm>
#include <stdexcept>

class FaultyComparator {
public:
    bool operator()(int a, int b) const {
        if (a == -1 || b == -1) {
            throw std::runtime_error("Invalid value encountered during comparison.");
        }
        return a == b;
    }
};

int main() {
    std::vector numbers = {-1, 10, 20, 30};

    try {
        auto it = std::find_if(numbers.begin(), numbers.end(), [](int n) {
            if (n == -1) {
                throw std::runtime_error("Faulty value found during comparison.");
            }
            return n == 20;
        });
        if (it != numbers.end()) {
            std::cout << "Element found: " << *it << std::endl;
        } else {
            std::cout << "Element not found." << std::endl;
        }
    } catch (const std::runtime_error& e) {
        std::cout << "Exception caught: " << e.what() << std::endl;
    }

    return 0;
}

Output

Exception caught: Faulty value found during comparison.

Explanation

  1. The program defines a lambda function inside std::find_if that throws an exception if the value -1 is encountered during the comparison.
  2. A vector numbers is initialized, containing a faulty value -1.
  3. The std::find_if function applies the lambda to each element. When it encounters the faulty value, the lambda throws an exception.
  4. The exception is caught in the try-catch block, and an error message is printed.

Example 2: Exception Thrown by an Iterator

This example demonstrates a case where a custom iterator throws an exception during iteration.

Program

</>
Copy
#include <iostream>
#include <vector>
#include <algorithm>
#include <stdexcept>

class FaultyIterator {
public:
    using iterator_category = std::input_iterator_tag;
    using value_type = int;
    using difference_type = std::ptrdiff_t;
    using pointer = const int*;
    using reference = const int&;

    FaultyIterator(const int* ptr, bool fail_after = false)
        : ptr(ptr), fail_after(fail_after), count(0) {}

    reference operator*() const {
        if (fail_after && count >= 2) {
            throw std::runtime_error("Iterator error during dereference.");
        }
        return *ptr;
    }

    FaultyIterator& operator++() {
        ++ptr;
        ++count;
        return *this;
    }

    bool operator!=(const FaultyIterator& other) const {
        return ptr != other.ptr;
    }

private:
    const int* ptr;
    bool fail_after;
    int count;
};

int main() {
    int arr[] = {1, 2, 3};

    try {
        auto it = std::find(
            FaultyIterator(arr, true), 
            FaultyIterator(arr + 3), 
            3
        );

        if (it != FaultyIterator(arr + 3)) {
            std::cout << "Element found: " << *it << std::endl;
        } else {
            std::cout << "Element not found." << std::endl;
        }
    } catch (const std::runtime_error& e) {
        std::cout << "Exception caught: " << e.what() << std::endl;
    }

    return 0;
}

Output

Exception caught: Iterator error during dereference.

Explanation

  1. The program defines a custom iterator FaultyIterator that throws a std::runtime_error exception after accessing two elements.
  2. An array arr is initialized with three elements.
  3. The std::find function searches for the value 3 in the range. The custom iterator throws an exception during the third access.
  4. The exception is caught in the try-catch block, and an error message is printed.