Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to insert into STL set?

Tags:

c++

set

stl

I'm having problems and I'm not sure I understand the STL documentation. Let's 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 foos into the set using my own comparator struct?

like image 309
Jay Kim Avatar asked Mar 22 '12 15:03

Jay Kim


1 Answers

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);
like image 105
Naveen Avatar answered Oct 29 '22 20:10

Naveen