C++ find()

Introduction

To find a certain element by value and return an iterator pointing at that element, we use the std::find function.

To search for a value of 5 in our vector, we use:

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

int main() //from  w ww.j  av  a2  s  .  com
{ 
    std::vector<int> v = { 1, 5, 2, 15, 3, 10 }; 
    auto result = std::find(v.begin(), v.end(), 5); 

    if (result!=v.end()) 
    { 
        std::cout << "Element found: " << *result; 
    } 
    else 
    { 
        std::cout << "Element not found."; 
    } 
} 

If the element is found, the function returns an iterator pointing at the first found element in the container.

If the value is not found the function returns an.end() iterator.

Instead of using container's .begin() and .end() member functions, we can also use a freestanding std::begin(container_name) and std::end(container_name) functions:

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

int main() //  w w w.ja  v a 2s . c om
{ 
    std::vector<int> v = { 1, 5, 2, 15, 3, 10 }; 
    auto result = std::find(std::begin(v), std::end(v), 5); 

    if (result!=std::end(v)) 
    { 
        std::cout << "Element found: " << *result; 
    } 
    else 
    { 
        std::cout << "Element not found."; 
    } 
} 

There is also a conditional std::find_if function which accepts a predicate.

Depending on the predicate value, the function performs a search on elements for which the predicate returns true.




PreviousNext

Related