Skip to main content

7.6) Sets


set<int> s;                  // creates empty set of integers
cout << s.size() << endl;    // prints 0
s.insert(7);
s.insert(42);
s.insert(42);
cout << s.size() << endl;    // prints 2 (42 stored only once)
if (s.find(7) != s.end()) {
  cout << "7 found" << endl;
}
  • Sets are made available via #include <set>
  • A set guarantees uniqueness of the elements it contains
  • A set keeps its elements in sorted order, not in order of insertion
  • Use the insert method to add a new element to a set
  • Use find to check whether a value is present; note that this method returns an iterator (see later)

See the page on sets at cppreference.com for further information.