find() in C++ STL (original) (raw)

Last Updated : 13 Apr, 2026

std::find() is a standard algorithm provided by the C++ Standard Template Library (STL). It is used to find the first occurrence of a given value in a specified range. The function works with containers that provide iterators, such as arrays, vectors, lists, and deques.

**Example: Using std::find() with sort()

C++ `

#include #include #include using namespace std;

int main() { vector v = {1, 3, 6, 2, 9};

// Sorting the vector
sort(v.begin(), v.end());

// Search for element 6
auto it = find(v.begin(), v.end(), 6);

// Print index
cout << distance(v.begin(), it);

return 0;

}

`

**Explanation:

Syntax

The std::find() is a C++ STL function defined inside ****** header file.

std::find(first, last, value);

**Parameters:

**Return Value:

**Time Complexity: O(n), as std::find() performs a linear search.
**Auxiliary Space: O(1), as no extra space is used.

The following examples demonstrate the use of find() function for different cases:

**Example 1: Search for an Element in the Array

C++ `

#include <bits/stdc++.h> using namespace std;

int main() { int arr[5] = {1, 3, 6, 2, 9};

// Search an element 6
auto it = find(arr, arr + 5, 6);

// Print index
cout << distance(arr, it);
return 0;

}

`

**Explanation: In this example, the std::find() function returns an iterator pointing to the value 6. The distance() function is then used to determine its index, which is 2.

**Example 2: Try to Find an Element That Is Not Present

C++ `

#include <bits/stdc++.h> using namespace std;

int main() { vector v = {1, 3, 6, 2, 9};

// Search an element 22
auto it = find(v.begin(), v.end(), 22);

  // Check if element is present
  if (it != v.end())
  
    // Print index
    cout << distance(v.begin(), it);
else
    cout << "Not Present";

return 0;

}

`

**Explanation: If the element is not found, std::find() returns the iterator to the end of the range. By comparing the returned iterator with v.end(), we can determine that the element is not present in the vector.