set: Unique, Sorted Values

A set holds values without duplicates, and keeps them sorted. Adding a value that's already there does nothing:

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

int main() {
    set<int> s;
    s.insert(5);
    s.insert(1);
    s.insert(5);          // already there: ignored
    s.insert(3);
    cout << "Size: " << s.size() << "\n";
    for (int x : s) {
        cout << x << " ";
    }
    cout << "\n";
    cout << "Has 3? " << s.count(3) << "\n";
    s.erase(3);
    cout << "Has 3? " << s.count(3) << "\n";
    return 0;
}

Output

Size: 3
1 3 5 
Has 3? 1
Has 3? 0

Removing duplicates

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

int main() {
    vector<string> visitors = {"ana", "ben", "ana", "cy", "ben", "ana"};
    set<string> unique(visitors.begin(), visitors.end());
    cout << visitors.size() << " visits from " << unique.size() << " people:\n";
    for (const string& name : unique) {
        cout << "- " << name << "\n";
    }
    return 0;
}

Output

6 visits from 3 people:
- ana
- ben
- cy
ContainerHoldsOrderDuplicates?
vectorvaluesthe order you add themyes
setvaluessortedno
mapkey → valuesorted by keyno duplicate keys
unordered_set / unordered_mapsame as aboveno particular orderno
HOME LABS COMMUNITY DASHBOARD