C++ set find
The find function in C++ set is employed to search for an element with a specified value, val. When the element is located, it yields an iterator indicating the element; alternatively, it provides an iterator pointing to the end of the set, which is set::end, if the element is not found.
Syntax
iterator find (const value_type& val) const; // until C++ 11
const_iterator find (const value_type& val) const; //since C++ 11
iterator find (const value_type& val); //since C++ 11
Parameter
val : indicates the specific value to search for within the set container.
Return value
If the element is located, it will provide an iterator referencing that element; otherwise, it will return an iterator pointing to the set's end, specifically set::end.
Complexity
Logarithmic in size.
Iterator validity
No changes.
Data Races
The container is accessed without modifying it in either the const or non-const versions.
Accessing and modifying the elements concurrently is considered safe as there are no mapped values being accessed.
Exception Safety
If an error is raised, the container remains unchanged.
Example 1
Let's examine a basic example to locate the item with the specified key value:
#include <iostream>
#include <set>
using namespace std;
int main(void) {
set<int> m = {100,200,300,400};
auto it = m.find(300);
cout << "Iterator points to " << *it << endl;
return 0;
}
Output:
Iterator points to 300
Example 2
Let's see a simple example to find the element:
#include <iostream>
#include <set>
using namespace std;
int main(void) {
set<char> m = {'a', 'b', 'c', 'd'};
auto it = m.find('e');
if ( it == m.end() ) {
// not found
cout<<"Element not found";
}
else {
// found
cout << "Iterator points to " << *it<< endl;
}
return 0;
}
Output:
Element not found
The find method locates the value 'e' within the set 'm'. If the value is not present in the set, a 'not found' message is returned; otherwise, the set is displayed.
Example 3
Let's see a simple example:
#include <iostream>
#include <set>
using namespace std;
int main()
{
char n;
set<char> example = {'a','b','c','d','e'};
cout<<"Enter the element which you want to search: ";
cin>>n;
auto search = example.find(n);
if (search != example.end()) {
cout << n<<" found and the value is " << *search << '\n';
} else {
cout << n<<" not found\n";
}
}
Output:
Enter the element which you want to search: b
b found and the value is b
In the previous example, the find method is employed to locate the element based on the value provided by the user.
Example 4
Let's see a simple example:
#include <iostream>
#include <set>
int main () {
std::set<int> myset;
std::set<int>::iterator it;
for (int i = 1; i <= 10; i++) myset.insert(i*10);
it = myset.find(40);
myset.erase (it);
myset.erase (myset.find(60));
std::cout << "myset contains:";
for (it = myset.begin(); it!=myset.end(); ++it)
std::cout << ' ' << *it;
std::cout << '\n';
return 0;
}
Output:
myset contains: 10 20 30 50 70 80 90 100