Home »
C++ STL
set::find() function in C++ STL
C++ STL set::find() function: Here, we are going to learn about the find() function of set in C++ STL (Standard Template Library).
Submitted by Radib Kar, on February 16, 2019
C++ STL set::find() function
The set::find() function is a predefined function, it is used to check whether an element belong to the set or not, if element finds in the set container it returns an iterator pointing to that element.
The function checks whether an element belong to the set or not. If an element belong to the set it returns the exact iterator position, else it returns st.end().
Syntax
set<T> st; //declaration
set<T>::iterator it; //iterator declaration
it=st.find( const T item);
Parameter(s)
It accepts an item.
Return value
It returns an iterator position.
Sample Input and Output
For a set of integer,
set<int> st;
set<int>::iterator it;
st.insert(4);
st.insert(5);
set content:
4
5
it=st.find(5);
Print *it; //prints 5
it= st.find(7) //it=st.end()
Header file
Header file to be included:
#include <iostream>
#include <set>
OR
#include <bits/stdc++.h>
Example
#include <bits/stdc++.h>
using namespace std;
void printSet(set<int> st) {
set<int>::iterator it;
cout << "Set contents are:\n";
for (it = st.begin(); it != st.end(); it++) cout << *it << " ";
cout << endl;
}
int main() {
cout << "Example of find function\n";
set<int> st;
set<int>::iterator it;
cout << "inserting 4\n";
st.insert(4);
cout << "inserting 6\n";
st.insert(6);
cout << "inserting 10\n";
st.insert(10);
printSet(st); // printing current set
// finding element 6
if (st.find(6) != st.end())
cout << "6 is present\n";
else
cout << "6 is not present\n";
// finding element 9
if (st.find(9) != st.end())
cout << "9 is present\n";
else
cout << "9 is not present\n";
return 0;
}
Output
Example of find function
inserting 4
inserting 6
inserting 10
Set contents are:
4 6 10
6 is present
9 is not present