Open In App

find() in C++ STL

Last Updated : 01 May, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

C++ find() is a built-in function used to find the first occurrence of an element in the given range. It works with any container that supports iterators, such as arrays, vectors, lists, and more. In this article, we will learn about find() function in C++.

C++
//Driver Code Starts{
#include <bits/stdc++.h>
using namespace std;

int main() {
//Driver Code Ends }

    vector<int> v = {1, 3, 6, 2, 9};

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

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

//Driver Code Starts{
  
    return 0;
}
//Driver Code Ends }

Output
2

Syntax of find()

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

C++
find(first, last, val);

Parameters:

  • first: Iterator to the first element of range.
  • last: Iterator to the theoretical element just after the last element of range.
  • val: Value to be searched.

Return Value:

  • If the value is found in the range, returns an iterator to its position otherwise return end iterator.

Examples of find()

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

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;
}

Output
2

In the above program, the find() function returns an iterator pointing to the value 6, and we use the distance() function to print the position of the value 6, which is 2.

Try to Find Element Which Not Present

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

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

    // Search an element 22
    auto it = find(v.begin(), v.end(), 22);
	
  	// Check if element is preset
  	if (it != v.end())
      
    	// Print index
        cout << distance(v.begin(), it);
    else
        cout << "Not Present";
  
    return 0;
}

Output
Not Present

Explanation: The find() function returns the iterator to the end of the range if the element is not found. So, we compared returned iterator to the v.end() to check if the element is present in the vector.



Next Article
Article Tags :
Practice Tags :

Similar Reads