The C++ std::unordered_set::find() function is used to find or search an element with key equivalent to key k in the container and returns an iterator if it is found, otherwise it returns an iterator to unordered_set::end().
The unordered_set is an associative container that contains a set of unique objects of type key. Every operation like insertion, search, and removal in an unordered_set has constant-time complexity.
SyntaxFollowing is the syntax for std::unordered_set::find() function.
iterator find ( const key_type& k ); const_iterator find ( const key_type& k ) const;Parameters
It returns an iterator to the element if the specified value is found; otherwise, it returns unordered_set::end if it is not found in the container.
Example 1Let's look at the following example, where we are going to demonstrate the usage of unordered_set::find() function.
#include <iostream> #include <string> #include <unordered_set> using namespace std; int main () { unordered_set<string> myset = { "sai","ram","krishna" }; //searching a key "ram" unordered_set<string>::const_iterator got = myset.find ("ram"); if ( got == myset.end() ) cout << "not found in myset"; else cout << *got << " is in myset"; cout << endl; return 0; }Output
If we run the above code it will generate the following output −
ram is in mysetExample 2
Consider the following example, where we are going to check whether the specified key is available or not.
#include <iostream> #include <string> #include <unordered_set> using namespace std; int main () { unordered_set<int> myset = { 10, 100, 1000, 10000 }; if ( myset.find(100) != myset.end() ) cout<< "100 is available in unordered set! "<<endl; if ( myset.find(1000) != myset.end() ) cout<< "1000 is available in unordered set! "<<endl; else cout<< "specified key is not available in unordered set! "<<endl; return 0; }Output
Following is the output of the above code −
100 is available in unordered set! 1000 is available in unordered set!Example 3
In the following example, we are going to erase the element that is found and display the left over elements.
#include <iostream> #include <unordered_set> using namespace std; int main (){ unordered_set<int> myUset{50, 500, 10, 100, 200}; unordered_set<int>::iterator it; it = myUset.find(50); myUset.erase(it); myUset.erase(myUset.find(10)); cout<<"myUset contains: "; for(it = myUset.begin(); it != myUset.end(); ++it) cout<<*it<<" "; return 0; }Output
Output of the above code is as follows −
myUset contains: 200 100 500
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4