0
0
CppHow-ToBeginner · 3 min read

How to Create a Set in C++: Syntax and Examples

In C++, you create a set using the std::set container from the <set> header. Declare it as std::set<Type> mySet; where Type is the data type of elements you want to store. Sets automatically store unique elements in sorted order.
📐

Syntax

The basic syntax to create a set in C++ is:

  • std::set<Type> setName; - creates an empty set of elements of type Type.
  • Type can be any data type like int, std::string, etc.
  • Sets store unique elements sorted by default.
cpp
std::set<int> mySet;
💻

Example

This example shows how to create a set, add elements, and print them. Notice duplicates are ignored and elements are sorted automatically.

cpp
#include <iostream>
#include <set>

int main() {
    std::set<int> numbers;
    numbers.insert(5);
    numbers.insert(3);
    numbers.insert(8);
    numbers.insert(3); // duplicate, will be ignored

    std::cout << "Set elements:" << std::endl;
    for (int num : numbers) {
        std::cout << num << " ";
    }
    std::cout << std::endl;
    return 0;
}
Output
Set elements: 3 5 8
⚠️

Common Pitfalls

Common mistakes when using sets include:

  • Trying to store duplicate elements (sets ignore duplicates automatically).
  • Assuming sets keep insertion order (they sort elements instead).
  • Forgetting to include <set> header.
  • Using std::set without std:: prefix or using namespace std;.
cpp
/* Wrong: duplicates allowed in vector but not in set */
#include <iostream>
#include <set>

int main() {
    std::set<int> s;
    s.insert(1);
    s.insert(1); // duplicate ignored
    std::cout << "Size: " << s.size() << std::endl; // prints 1
    return 0;
}
Output
Size: 1
📊

Quick Reference

OperationSyntaxDescription
Create setstd::set mySet;Declares an empty set of Type elements
Insert elementmySet.insert(value);Adds value to the set if not present
Check sizemySet.size();Returns number of unique elements
Iteratefor(auto x : mySet) { ... }Loops through elements in sorted order
Erase elementmySet.erase(value);Removes value from the set if present

Key Takeaways

Use std::set<Type> from <set> to create a set in C++.
Sets store unique elements automatically sorted by value.
Insert elements with insert(); duplicates are ignored.
Remember to include <set> and use the std:: prefix or namespace.
Sets do not preserve insertion order, they keep elements sorted.