Sets

Sets

 
In C++, a set is a container class template from the Standard Template Library (STL) that stores unique elements in a sorted order.
A set stores only unique elements and does not allow duplicates. Each element in a set is sorted according to their comparison operator, which is by default the less-than operator.
Sets are implemented as binary search trees, which provides efficient insertion, deletion, and searching of elements. They have a time complexity of O(log n) for these operations.
Sets are useful in situations where you need to store unique elements in a sorted order. For example, you could use a set to store a list of unique employee IDs in a company. The set would automatically sort the IDs and remove any duplicates.
You can also use a set to implement various algorithms such as finding the intersection, union, or difference of two sets. The set container provides a set of member functions to perform these operations.
 
 
#include <iostream> #include <set> using namespace std; int main() { // Create a set of integer values set<int> mySet; // Insert elements in the set mySet.insert(10); mySet.insert(20); mySet.insert(30); mySet.insert(40); mySet.insert(50); // Print the elements in the set cout << "Current set elements: " << endl; for (auto it = mySet.begin(); it != mySet.end(); it++) { cout << *it << endl; } cout << endl; // Search for an element in the set auto it = mySet.find(30); if (it != mySet.end()) { cout << "Element found in the set: " << *it << endl; } else { cout << "Element not found in the set" << endl; } // Erase an element from the set mySet.erase(40); // Print the modified set cout << "Modified set after erasing 40: " << endl; for (auto it = mySet.begin(); it != mySet.end(); it++) { cout << *it << endl; } cout << endl; // Clear all of the elements of the set mySet.clear(); // Check if the set is empty if (mySet.empty()) { cout << "Set is empty" << endl; } else { cout << "Set is not empty" << endl; } return 0; }
 
This implementation creates an empty set of integer values mySet. It then adds elements to the set using the insert() function. The elements are printed to the console using a for loop and the begin() and end() functions of the set.
The find() function is used to search for an element in the set. If the element is found, its value is printed to the console.
The erase() function removes an element from the set. The modified set is printed to the console.
The clear() function deletes all of the elements of the set, and the empty() function checks if the set is empty. Finally, the program returns 0.
 
 
PRACTICE PROBLEMS :
  1. Merge Similar Items
  1. Display Table of Food Orders in a Restaurant