A set in C++ is a collection of unique elements stored in a specific order. It automatically keeps the elements sorted and does not allow duplicates.
characteristics of sets
1. Unique Elements: Sets do not allow duplicate elements. If you try to insert a duplicate element, the set will ignore it.
2. Sorted: By default, elements are stored in ascending order. However, you can specify a custom sorting criterion by using a comparator.
3. Efficient Searching: Sets are typically implemented as balanced binary search trees (usually Red-Black trees), which makes searching, inserting, and deleting elements efficient. Operations like insertion, deletion, and search are logarithmic in time complexity (O(log n)).
Example:
#include <iostream>
#include <set>
using namespace std;
int main() {
set<int> mySet;
mySet.insert(10);
mySet.insert(20);
mySet.insert(30);
mySet.insert(10); // Duplicate, will not be added
// Iterating through the set and printing the elements
for (int val : mySet) {
cout << val << " ";
}
return 0;
}
Explanation:
- The set automatically removes the duplicate 10.
- It stores the elements in sorted order: 10, 20 and 30.
Output:
Complete Example:
#include <iostream>
#include <set>
using namespace std;
int main() {
set<int> mySet;
// Adding elements
mySet.insert(10);
mySet.insert(20);
mySet.insert(30);
mySet.insert(10); // This will not be added, as 10 is already in the set
// Displaying elements (automatically sorted in ascending order)
cout << "Elements in the set: ";
for (int num : mySet) {
cout << num << " ";
}
cout << endl;
// Checking size
cout << "get the size: " << mySet.size() << endl;
// Searching for an element
if (mySet.find(5) != mySet.end()) {
cout << "5 found in the set." << endl;
}
// Erasing an element
mySet.erase(3);
cout << "After erasing 3, set size: " << mySet.size() << endl;
return 0;
}
Example:
get the size: 3
After erasing 3, set size: 3
C++ sets – Questions and Answers
Q 1: What is set in STL?
Ans: Collection of unique elements.
Q 2: Are duplicates allowed?
Ans: No.
Q 3: Is set ordered?
Ans: Yes.
Q 4: Internal implementation?
Ans: Balanced binary tree.
Q 5: Time complexity of insert?
Ans: O(log n).
C++ sets – Objective Questions (MCQs)
Q1. Which header file is used for set in C++?
Q2. What does a C++ set store?
Q3. Which function is used to insert an element into a set?
Q4. What is the default order of elements in a std::set?
Q5. Can a C++ set contain duplicate values?