๐Ÿงฉ C++ STL & Data Structures
Estimated reading: 3 minutes 32 views

๐Ÿ“ C++ Sets โ€“ Store Sorted Unique Elements with std::set


๐Ÿงฒ Introduction โ€“ Why Use std::set in C++

In C++ applications where duplicates are not allowed and fast search, insertion, and deletion are required, std::set is the ideal choice. It stores elements in a sorted order and provides logarithmic time complexity for all operations, thanks to its balanced tree structure.

๐ŸŽฏ In this guide, youโ€™ll learn:

  • What std::set is and how it works
  • Key operations like insert(), find(), erase()
  • How to use iterators and custom sort orders
  • Best practices and real-world use cases

๐Ÿ“˜ What Is a C++ Set?

A std::set is an ordered associative container that contains only unique keys. It stores the keys in ascending order by default using a Red-Black Tree (balanced BST).

Include the header:

#include <set>

Declare a set:

set<int> s;

๐Ÿ’ป Code Examples โ€“ With Output

โœ… Insert and Traverse

#include <iostream>
#include <set>
using namespace std;

int main() {
    set<int> s;
    s.insert(30);
    s.insert(10);
    s.insert(20);
    s.insert(10); // Duplicate ignored

    for (int x : s) cout << x << " ";
    return 0;
}

๐ŸŸข Output:

10 20 30

โœ… Search and Erase

if (s.find(20) != s.end())
    s.erase(20);

๐Ÿงฉ Set Member Functions

FunctionDescription
insert(val)Adds a new element (if not present)
erase(val)Removes element
find(val)Returns iterator to element if found
count(val)Returns 1 if element exists, else 0
size()Returns number of elements
clear()Removes all elements
begin()/end()Start/end iterators for traversal

๐Ÿ”€ Custom Sort Order with Comparator

struct Desc {
    bool operator()(int a, int b) const {
        return a > b; // Descending
    }
};

set<int, Desc> descSet;

๐Ÿ” Iterating a Set

for (set<int>::iterator it = s.begin(); it != s.end(); ++it)
    cout << *it << " ";

๐Ÿ†š Set vs Multiset vs Unordered Set

Featuresetmultisetunordered_set
Duplicates allowed?โŒ Noโœ… YesโŒ No
Orderโœ… Sortedโœ… SortedโŒ Unordered
Lookup complexityO(log n)O(log n)O(1) average
Underlying structureBalanced treeBalanced treeHash table

๐Ÿ’ก Best Practices & Tips

๐Ÿ“˜ Use count() if you only need to check for existence
๐Ÿ’ก For heavy insert/delete workloads, consider unordered_set
โš ๏ธ Avoid modifying set elements via iteratorsโ€”sets reorder elements automatically
๐Ÿ“ฆ Use a custom comparator for descending order or complex types


๐Ÿ› ๏ธ Use Cases for Sets

๐Ÿงฎ Unique Element Tracking โ€“ Email lists, usernames, identifiers
๐Ÿ“Š Sorted Data Retrieval โ€“ Maintain live sorted datasets
๐Ÿ” Efficient Searching โ€“ Membership tests and quick lookups
๐Ÿ“ฅ Event Logs โ€“ Avoid duplicate event IDs
๐Ÿง  Mathematical Sets โ€“ Implement union, intersection, difference


๐Ÿ“Œ Summary โ€“ Recap & Next Steps

๐Ÿ” Key Takeaways:

  • std::set stores unique, automatically sorted elements
  • Efficient for searching, insertion, and deletion (O(log n))
  • Supports iterators and custom comparators

โš™๏ธ Real-World Relevance:
C++ sets are used in simulations, indexes, validation systems, constraint checkers, and anywhere uniqueness and order are critical.

โœ… Next Steps:
Learn about C++ Maps to associate keys with values in sorted order.


โ“FAQ โ€“ C++ Sets

โ“ Are duplicates allowed in std::set?
โŒ No. Use multiset if duplicates are needed.

โ“ Can I change an element in a set directly?
โš ๏ธ No. You must remove and re-insert to modify value.

โ“ How is set sorted?
By default in ascending order using < operator.

โ“ Can I sort a set in descending order?
โœ… Yes. Use a custom comparator.

โ“ Is find() faster than looping through the set?
โœ… Yes. find() uses binary search (O(log n)).


Share Now :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

C++ Sets

Or Copy Link

CONTENTS
Scroll to Top