find of STL algorithm

Keywords: PHP

Definition

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

Effect

Find the first element equal to val between the ranges [first, last]. Find the iterator that returns the first matching element, otherwise return the last iterator.
This function uses operator = = to compare elements and val one by one.
The modified function template is equivalent to the following:

template<class InputIterator, class T>
  InputIterator find (InputIterator first, InputIterator last, const T& val)
{
  while (first!=last) 
  {
    if (*first==val) 
    {
        return first;
    }
    ++first;
  }
  return last;
}

parameter

first,last

Enter the iterator as the start and end of the squence, respectively. Search in the range [first, last], including first, excluding last.

val

The value searched in the range. T is the type that supports the comparison operation with InputIterator through the operator = = (the element is on the left side of the operator and val is on the right side)

Return value

Returns the iterator of the first element when the = = compare operation is true. Otherwise, return to last.

Example

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

using namespace std;

int main( int argc, char **argv )
{
    vector<int>::iterator ret;
    vector<int> numbers{1, 2, 7, 2,3};

    //Appear once
    ret = find(numbers.begin(), numbers.end(), 1);
    if ( ret == numbers.end() )
    {
        cout << "not found 1" << endl;
    }
    else
    {
        cout << "found 1" << endl;
    }

    //Appear many times
    ret = find(numbers.begin(), numbers.end(), 2);
    if ( ret == numbers.end() )
    {
        cout << "not found 2" << endl;
    }
    else
    {
        //First element found
        cout << "found 2 and next element is:"<< *(ret+1) << endl;
    }

    //Did not appear
    ret = find(numbers.begin(), numbers.end(), 5);
    if ( ret == numbers.end() )
    {
        cout << "not found 5" << endl;
    }
    else
    {
        cout << "found 5" << endl;
    }

    return 0;
}

Posted by ionik on Tue, 22 Oct 2019 12:02:08 -0700