C++ 如何插入stl集合?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9824883/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-27 13:19:43  来源:igfitidea点击:

how to insert into stl set?

c++stlset

提问by Jay Kim

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

我遇到了问题...我不确定我是否理解 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;
}

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

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

回答by Naveen

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

你可以使用set::insert方法,没有什么可做的。例如,

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

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