I have forgotten
my Password

Or login with:

  • Facebookhttp://facebook.com/
  • Googlehttps://www.google.com/accounts/o8/id
  • Yahoohttps://me.yahoo.com

find

Searches for the first element with the passed value

Definition

The find() algorithm is defined in the standard header <algorithm> and in the nonstandard backward-compatibility header <algo.h>.

Interface

#include<algorithm>
template <class InputIterator, class Type>
   InputIterator find(
      InputIterator first, 
      InputIterator last, 
      const Type& val
   );

Parameters:

Parameter Description
first An input iterator addressing the position of the first element in the range to be searched for the specified value
last An input iterator addressing the position one past the final element in the range to be searched for the specified value
val The value to be searched for

Description

Locates the position of the first occurrence of an element in a range that has a specified value.

The return value is an input iterator addressing the first occurrence of the specified value in the range being searched. If no such value exists in the range, the iterator returned addresses the last position of the range, one past the final element.

The operator== used to determine the match between an element and the specified value must impose an equivalence relation between its operands.

Complexity

At most, performs as many comparisons as the number of elements in the range [first,last).
Example:

Example - find function
Problem
The following example finds an integer in a vector of integers.
Workings
#include <algorithm>
#include <vector>
 
int main()
{
  int n1 = 3;
  int n2 = 5;
 
  std::vector<int> v{0, 1, 2, 3, 4};
  std::vector<int>::iterator result1, result2;
 
  result1 = std::find(v.begin(), v.end(), n1);
  result2 = std::find(v.begin(), v.end(), n2);
 
  if (result1 != v.end()) 
      std::cout <<"v contains: "<<n1<<"\n";
  else
      std::cout <<"v does not contain: "<<n1<<"\n";
 
  if (result2 != v.end()) 
      std::cout <<"v contains: "<<n2<<"\n";
  else 
      std::cout <<"v does not contain: "<<n2<<"\n";
 
  return 0;
}
Solution
Output:

v contains: 3
v does not contain: 5
References

See Also