【问题标题】:How to insert into STL set?如何插入到 STL 集中?
【发布时间】:2012-04-07 04:01:51
【问题描述】:

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

如何使用我自己的比较器结构将结构foos 插入set

【问题讨论】:

  • 您尝试使用insert 方法了吗?你得到了什么错误?

标签: c++ stl set


【解决方案1】:

您可以使用set::insert 方法,无需多做。例如,

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

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

【讨论】:

  • fooset.insert(foo); // 像那样?它会被插入正确的位置吗?
  • 正如我在示例代码中所示,fooset.insert(f1);,在插入set 时将使用您提供的比较函子来确定对象的正确位置。
  • @JayKim 如果您依赖于集合中元素的位置(尽管在 STL 中定义良好)来做某事,那么您可能使用了错误的数据结构。
  • @manasij - 我认为使用集合中的上限和下限是进行范围搜索的好方法?没有?
  • @SohailSi std::set 没有这样的运算符。
猜你喜欢
  • 2013-11-21
  • 2011-04-02
  • 2023-03-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多