C++ – how to insert into stl set

c++setstl

I'm having problems…I'm not sure I understand the STL documentation. Lets say I have this:

#include <set>
...

struct foo
{
    int bar;
};

struct comp
{
    inline bool operator()(const foo& left,const foo& right)
    {
        return left.bar < right.bar;
    }
};

int main()
{
    std::set<foo,comp> fooset;  // Uses comparison struct/class object comp to sort the container

    ...

    return 0;
}

How do I insert struct foo's into the set using my own comparator struct?

Best Solution

You can use the set::insert method, there is nothing more to do. For example,

foo f1, f2;
f1.bar = 10;
f2.bar = 20;

fooset.insert(f1);
fooset.insert(f2);
Related Question