Open In App

std::find in C++

std::find is a function defined inside <algorithm> header file that finds the element in the given range. It returns an iterator to the first occurrence of the specified element in the given sequence. If the element is not found, an iterator to the end is returned.

Syntax:



input_iterator std::find(input_iterator first, input_iterator last, const T& value);

Parameters:

Return Value :



NOTE: input_iterator is the iterator type of the used container and T is the typename defined in the function template.

Example:




// C++ program to Demonstrate
// std::find for vectors
#include <bits/stdc++.h>
 
// Driver code
int main()
{
  std::vector<int> vec{10, 20, 30, 40};
 
  // Iterator used to store the position
  // of searched element
  std::vector<int>::iterator it;
 
  // Print Original Vector
  std::cout << "Original vector :";
   
  for (int i = 0; i < vec.size(); i++)
    std::cout << " " << vec[i];
 
  std::cout << "\n";
 
  // Element to be searched
  int ser = 30;
 
  // std::find function call
  it = std::find(vec.begin(),
                 vec.end(), ser);
  if (it != vec.end())
  {
    std::cout << "Element " << ser <<
                 " found at position : ";
    std::cout << it - vec.begin() <<
                 " (counting from zero) \n";
  }
  else
    std::cout << "Element not found.\n\n";
 
  return 0;
}

Output
Original vector : 10 20 30 40
Element 30 found at position : 2 (counting from zero) 

Time Complexity: O(n)
Auxiliary Space: O(1)

NOTE: std::find() function is defined inside <algorithm> header file. So, we need to include that header file before using find function.

As we can see that the time complexity of the std::find() is O(n) and it also works on unsorted sequences, we can conclude that it uses the linear search algorithm in its implementation.

Related Articles: 


Article Tags :
C++