Finding an element in a container

To find an element in a C++ container, or indeed between any pair of InputIterators, use find or find_if.

Use find to find an element with a value you specify. It will return an iterator pointing to the element being sought if successful, and the end of the range if it isn’t found.


#include <vector>
#include <algorithm>
#include <iostream>

int main()
{
    std::vector<unsigned int>numbers(3);
    std::iota(numbers.begin(), numbers.end(), 4); // Populate with 4, 5, 6
    if (std::find(numbers.begin(), numbers.end(), 5) != numbers.end()) {
        std::cout << "Found 5" << "\n";
    }
    else {
        std::cout << "5 not found" << "\n";
    }
}

Use find_if to find an element that satisfies a predicate.

#include <vector>
#include <algorithm>
#include <iostream>

struct divides_by_3
{
public:
    bool operator()(int i)
    {
        return i % 3 == 0;
    }
};

int main()
{
    std::vector<unsigned int>numbers(3);
    std::iota(numbers.begin(), numbers.end(), 4); // Populate with 4, 5, 6
    std::vector<unsigned int>::const_iterator it = 
            std::find_if(numbers.begin(), numbers.end(), divides_by_3());
    if (it != numbers.end()) {
        std::cout << "Found a number that divides by 3: " << *it << "\n";
    }
    else {
        std::cout << "Not found" << "\n";
    }
}