A std::set is a container class in the C++ Standard Template Library (STL) that stores a collection of unique elements in a sorted order. It is implemented as a balanced binary search tree, which allows for efficient insertion, removal, and lookup of elements.
A std::multiset is similar to std::set but it allows duplicate elements to be stored.
Here is an example of creating and using a std::set and std::multiset:
Copy code
#include <set>
#include <iostream>
int main() {
// Create a set of integers
std::set<int> mySet;
// Insert the numbers 1-5 into the set
mySet.insert(3);
mySet.insert(1);
mySet.insert(5);
mySet.insert(2);
mySet.insert(4);
// Print the set
for (auto i : mySet) {
std::cout << i << " ";
}
std::cout << std::endl;
// Check if the set contains the number 3
if (mySet.count(3)) {
std::cout << "The set contains the number 3." << std::endl;
} else {
std::cout << "The set does not contain the number 3." << std::endl;
}
// Remove the number 3 from the set
mySet.erase(3);
// Print the set
for (auto i : mySet) {
std::cout << i << " ";
}
std::cout << std::endl;
// Create a multiset of integers
std::multiset<int> myMultiset;
// Insert the numbers 1-5 into the multiset
myMultiset.insert(3);
myMultiset.insert(1);
myMultiset.insert(5);
myMultiset.insert(2);
myMultiset.insert(4);
myMultiset.insert(3);
// Print the multiset
for (auto i : myMultiset) {
std::cout << i << " ";
}
std::cout << std::endl;
// Check if the multiset contains the number 3
if (myMultiset.count(3)) {
std::cout << "The multiset contains the number 3." << std::endl;
} else {
std::cout << "The multiset does not contain the number 3." << std::endl;
}
// Remove all occurrences of the number 3 from the multiset
myMultiset.erase(3);
// Print the multiset
for (auto i : myMultiset) {
std::cout << i << " ";
}
std::cout << std::endl;
return 0;
}
This program creates a std::set called mySet and std::multiset called myMultiset.
It then uses the insert() function to insert the numbers 1-5 into the mySet. After
that it will print the set using range based for loop and it will check if the set contains the number 3 using the count() function. Then it will remove the number 3 from the set using the erase() function. After that it will print the set again.
Then it will insert the numbers 1-5 into the myMultiset and it will insert the number 3 twice, so there will be two occurrences of the number 3 in the multiset. After that it will print the multiset using range based for loop and it will check if the multiset contains the number 3 using the count() function. Then it will remove all occurrences of the number 3 from the multiset using the erase() function. After that it will print the multiset again.
As we can see, the main difference between std::set and std::multiset is that std::set stores unique elements, whereas std::multiset allows for duplicate elements to be stored.
To embed this project on your website, copy the following code and paste it into your website's HTML: