我想将 STL 设置为:
- 在这个集合中插入一个
struct
,比如struct {int id, string info};
- 每次插入,如果id存在,则不插入
- 使元素排序
我尝试了以下代码:
#include <iostream>
#include <set>
using namespace std;
struct song
{
int m_id;
int m_hot;
song(int id,int hot)
{
this->m_id = id;
this->m_hot = hot;
}
bool operator<(const struct song & right)const
{
if(this->m_id == right.m_id) { // remove duplicated
return false;
}
if(this->m_hot != right.m_hot)
{
return this->m_hot > right.m_hot;
}
else
{
return this->m_id > right.m_id;
}
}
};
int main()
{
std::set<song> mySet;
song s1(10,100);
song s2(40,700);
song s3(40,300);
song s4(30,200);
song s5(300,200);
song s6(300,900);
mySet.insert(s1);
mySet.insert(s2);
mySet.insert(s3);
mySet.insert(s4);
mySet.insert(s5);
mySet.insert(s6);
for(auto it:mySet)
{
std::cout<<"id:"<<it.m_id<<",hot:"<<it.m_hot<<std::endl;
}
}
输出是:
id:300,hot:900
id:40,hot:700
id:300,hot:200
id:30,hot:200
id:10,hot:100
如您所见,id 40 删除重复成功,但 300 失败。 我认为 id 300 部分不应出现两次,有人可以帮我吗?
最佳答案
你的 operator<
不满足strict weak ordering并且您的要求不能这样表达。
问题是你有两个 key ,m_id
(为了唯一性)和 m_hot
(用于订购)。您不能选择仅通过 m_hot
订购.您总是必须按两者排序(并忽略等效比较元素),并且您只能选择优先级。因此,您无法在 {id=0, hot=0}
之间建立等价关系。和 {id=0, hot=1}
.
^ 如果你的比较器不能写成 std::tie(lhs.keys...) < std::tie(rhs.keys...)
,这不好。
目前只能想到m_hot
推迟下单在你需要它的地方(通过复制到 std::vector
并对其进行排序或插入到具有不同比较器的 std::set
)。
关于c++ - 如何使用自定义的重复判断函数做一个集合?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56097680/