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

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.

Prototype:

    set<T> st; //declaration
    set<T>::iterator it; //iterator declaration
    it=st.find( const T item); 

Parameter: const T item

Return type: Iterator position

Usage:

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().

Example:

    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 to be included:

    #include <iostream>
    #include <set>
    OR
    #include <bits/stdc++.h>

C++ implementation:

#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




Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.



Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.