小编Wag*_*nin的帖子

为什么 std::set 允许我插入重复的(非唯一的)自定义元素?

我需要创建一组自定义项目:

  1. 按优先级排序
  2. 不能有重复的名字。

在这个例子中,我使用std::set和一个重载的operator<( )。据我所知,std::set使用operator<( )进行排序和唯一性检查。但是我的代码失败了,因为我能够插入具有重复名称的项目:

#include <iostream>
#include <set>



struct Item
{
    std::string name;
    int priority;
};



bool operator<( const Item& a, const Item& b ) 
{
    // Always returns false if names are equal.
    // Set should consider elements equal when a < b is false and b < a is also false.
    if( a.name == b.name )
        return false;

    return ( a.priority < b.priority );
}



int main()
{ …
Run Code Online (Sandbox Code Playgroud)

c++

0
推荐指数
1
解决办法
94
查看次数

标签 统计

c++ ×1