Code Yarns ‍👨‍💻
Tech BlogPersonal Blog

C++ STL: Set

📅 2010-Mar-05 ⬩ ✍️ Ashwin Nanjappa ⬩ 🏷️ cpp, sets, stl ⬩ 📚 Archive

One can create and use a STL vector of objects of a class without any extra code. To do the same with a STL set of objects of a class one needs to add a comparison function to the class. This is required because a set keeps its elements sorted.

A bare bones example:

#include <set>

class MyObj
        int _item;
        MyObj::MyObj(int item) : _item(item) {}

        // Comparison
        bool MyObj::operator < (const MyObj& other) const
            return _item < other._item;

int main()
    std::set<MyObj> mySet;

    return 0;