Open In App

set find() Function in C++ STL

Last Updated : 13 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The std::set::find() is a built-in function in C++ STL that is used to find an element in the set container. It is a member function of std::set container so we can use it directly with any set object.

Syntax

 set_name.find(key) 

Parameters

  • key: The element which we have to find.

Return Value

  • If the element is found, it returns an iterator to its position in the set.
  • If the element is not found, then it returns the iterator to the end.

Finding elements in a set is straightforward with the find() function.

Example of set::find()

C++
// C++ program to demonstrate the use of
// set::find() function
#include <bits/stdc++.h>
using namespace std;

int main() {

    // Create a set
    set<int> st;
    st.insert(11);
    st.insert(14);
    st.insert(2);
    st.insert(15);
    st.insert(3);

    // key1 find (exist in the set)
    int key1 = 3;

    // key2 find (does not exist in the set)
    int key2 = 1;

    // Check if key1 is found
    if (st.find(key1) != st.end())
        cout << "Key '" << key1 << "' found" << endl;

    // Element not present
    else
        cout << "Key '" << key1 << "' not found!" << endl;

    // Check if key2 is found
    if (st.find(key2) != st.end())
        cout << "Key '" << key2 << "' found" << endl;

    // key2 not found
    else
        cout << "Key '" << key2 << "' not found!" << endl;

    return 0;
}

Output
Key '3' found
Key '1' not found!

Complexity Analysis of set::find()

  • Time Complexity: O(log n), where n is the number of elements.
  • Space Complexity: O(1)



Next Article
Article Tags :
Practice Tags :

Similar Reads