
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Set Find Function in C++ Programming STL
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()
The std::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
Following is the syntax is as follows:
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 Scenario
Following is the example for Input and Output Scenario:
Input: set<int> myset = {10, 20, 40, 80, 90}; myset.find(40); Output: element found
Let us go through the program examples for better understanding.
Example 1: Find a Value using std::set
In this example, we use std::find() function to locate the value 40 in a set and then iterates from that point to print all elements to the end.
#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; }
If we run the above code then it will generate the following output:
Elements after 40 are: 40 80 90
Example 2: Remove elements from std::set Using find() and erase()
In this example, we demonstrate how to remove specific elements from a set using find() to locate and erase() to delete them.
#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; }
If we run the above code then it will generate the following output:
Elements are : 2 8