Set find() function in C++ programming STL

C++Server Side ProgrammingProgramming

In this article we are going to discuss the set::find() function in C++ STL, their syntax, working and their return values.

What is Set in C++ STL?

Sets in C++ STL are the containers which must have unique elements in a general order. Sets must have unique elements because the value of the element identifies the element. Once added a value in a set container later can’t be modified, although we can still remove or add the values to the set. Sets are used as binary search trees.

What is set::find()

find() function is an inbuilt function in C++ STL, which is defined in header file. This function is used to find an element or a value in a set container. find() returns an iterator which points to the position of the element which is searched. If the element is not present in the set, then it returns the element just after the last element of the set container.

Syntax

Set1.find(const type_t& element);

Parameter

This function accepts one parameter, i.e., element which is to be found.

Return value

This function returns an iterator which points to the element which is to be found.

Example

Input: set<int> myset = {10, 20, 40, 80, 90};
myset.find(40);
Output: element found

Example

 Live Demo

#include <bits/stdc++.h>
using namespace std;
int main(){
   set<int> mySet;
   mySet.insert(10);
   mySet.insert(20);
   mySet.insert(90);
   mySet.insert(80);
   mySet.insert(40);
   auto temp = mySet.find(40);
   cout<<"Elements after 40 are: ";
   for (auto i = temp; i != mySet.end(); i++)
      cout << *i << " ";
   return 0;
}

Output

If we run the above code then it will generate the following output −

Elements after 40 are: 40 80 90

Example

 Live Demo

#include <iostream>
#include <set>
int main (){
   std::set<int> mySet;
   std::set<int>::iterator i;
   for(int i=1; i<=4; i++)
      mySet.insert(i*2);
   i = mySet.find(6);
   mySet.erase(i);
   mySet.erase(mySet.find(4));
   std::cout<<"elements are : ";
   for (i = mySet.begin(); i != mySet.end(); ++i)
      std::cout << ' ' << *i;
   std::cout << '\n';
   return 0;
}

Output

If we run the above code then it will generate the following output −

Elements are : 2 8
raja
Published on 05-Mar-2020 10:11:05
Advertisements