如何插入到stl集中?

Jay*_*Kim 9 c++ stl set

我遇到了问题......我不确定我是否理解STL文档.让我说我有这个:

#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;
}
Run Code Online (Sandbox Code Playgroud)

如何使用我自己的比较器结构将struct foo插入到集合中?

Nav*_*een 15

你可以使用这个set::insert方法,没有更多的事情要做.例如,

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

fooset.insert(f1);
fooset.insert(f2);
Run Code Online (Sandbox Code Playgroud)

  • @JayKim如果你依赖于集合中元素的位置(虽然在STL中定义得很好)来做某事,你可能使用了错误的数据结构. (3认同)