In C++, the `set` is a container class that stores a collection of unique elements in a specific order. It is part of the Standard Template Library (STL) and provides a way to efficiently store and access elements without duplicates.
To use the `set` container in C++, you need to include the `<set>` header file. Here's an example of how to create and use a set in C++:
```cpp
#include <iostream>
#include <set>
int main() {
// Create a set of integers
std::set<int> mySet;
// Insert elements into the set
mySet.insert(5);
mySet.insert(2);
mySet.insert(8);
mySet.insert(2); // Duplicate value, will be ignored
// Iterate over the elements in the set
for (const auto& element : mySet) {
std::cout << element << " ";
}
std::cout << std::endl;
// Check if an element exists in the set
if (mySet.count(8) > 0) {
std::cout << "Element 8 is present in the set." << std::endl;
} else {
std::cout << "Element 8 is not present in the set." << std::endl;
}
// Remove an element from the set
mySet.erase(2);
// Check the size of the set
std::cout << "Size of the set: " << mySet.size() << std::endl;
// Clear all elements from the set
mySet.clear();
// Check if the set is empty
if (mySet.empty()) {
std::cout << "The set is empty." << std::endl;
} else {
std::cout << "The set is not empty." << std::endl;
}
return 0;
}
```
In this example, we create a set `mySet` and insert some elements into it. Since sets store unique elements, the duplicate value `2` is ignored. We then iterate over the set and print its elements.
Next, we demonstrate how to check if a specific element exists in the set using the `count` function. We also remove an element using the `erase` function and check the size of the set using the `size` function.
Finally, we clear all the elements from the set using the `clear` function and check if the set is empty using the `empty` function.
Remember to compile and run the program to see the output.
No comments:
Post a Comment