This tutorial will discuss how to find elements in multiset in C++?.
In C++, if we have a multiset of integers and want to find an element within it, the multiset offers a ‘find()’ function. This function takes a value as an argument and returns an iterator pointing to the first occurrence of that value. Since a multiset can contain duplicate elements, the ‘find()’ function targets the first occurrence of the specified element. If the sought value doesn’t exist in the multiset, the function returns an iterator that points to the position just past the last element of the multiset, equivalent to what the ‘end’ function returns.
Thus, we can use the ‘find()’ function to get an iterator for a specific value within the multiset, and subsequently access the value.
For instance, in the example below, we search for the value 44 in the multiset. If the iterator is valid, we’ll print that value. Since 44 already exists in the multiset, it will return a valid iterator.
#include <iostream> #include <set> int main() { std::multiset<int> numSet {11, 22, 33, 44, 33, 44, 33, 55}; // Look for value 44 in multiset std::multiset<int>::iterator it = numSet.find(44); // Check if iterator is valid if(it != numSet.end()) { std::cout<< "Element: " << *it << std::endl; } }
Output:
Element: 44
In another example, we’ll try to find the value 80 in the multiset. Since 80 isn’t present, the function will return an iterator pointing to the end of the multiset.
#include <iostream> #include <set> int main() { std::multiset<int> numSet {11, 22, 33, 44, 33, 44, 33, 55}; // Look for value 80 in multiset auto it = numSet.find(80); // Check if iterator is valid if(it != numSet.end()) { std::cout<< "Element: " << *it << std::endl; } else { std::cout<< "Element Not found in MultiSet"<< std::endl; } }
Output:
Element Not found in MultiSet
In essence, the ‘find’ function is a valuable tool for searching for specific values within a multiset.
Let’s see the complete example,
#include <iostream> #include <set> int main() { std::multiset<int> numSet {11, 22, 33, 44, 33, 44, 33, 55}; // Look for value 44 in multiset std::multiset<int>::iterator it = numSet.find(44); // Check if iterator is valid if(it != numSet.end()) { std::cout<< "Element: " << *it << std::endl; } // Look for value 80 in multiset auto it2 = numSet.find(80); // Check if iterator is valid if(it2 != numSet.end()) { std::cout<< "Element: " << *it << std::endl; } else { std::cout<< "Element Not found in MultiSet"<< std::endl; } return 0; }
Output
Element: 44 Element Not found in MultiSet
Summary
Today, we learned how to find elements in multiset in C++?.