operator <=虽然让多个重复的元素都在set中
#include <iostream>
#include <set>
using namespace std;
class stru{
public:
stru(int a, int b): x(a), y(b){}
int x;
int y;
};
bool operator<(const stru& a, const stru& b) //比较的是x的值
{
return a.x <= b.x;
}
int main()
{
//创建
set<stru> st;
//插入
st.emplace(stru(8, 38));
st.emplace(stru(8, 39));
st.emplace(stru(9, 40)); //添加成功,因为multiset可以有重复的值,也就是说有x = 10的stru也可以。
st.emplace(stru(9, 41)); //添加成功
st.emplace(stru(10, 42));
st.emplace(stru(10, 43));
st.emplace(stru(10, 44));
auto res = st.emplace(stru(10, 45));
//查看
for (auto it = st.rbegin(); it != st.rend(); it++) //10-40 9-43 9-45 8-40 7-35 6-30 5-25 4-20 3-15 2-10 1-5 0-0
cout<<(*it).x<<"-"<<(*it).y<<" ";
cout<<endl;
// 查找,查找出符合比较函数的第一项
auto it = st.find(stru(10, 43)); //和上面一样,只会找x = 9的第一项。
cout<<"查找出符合比较函数的第一项:"<< it->x <<" "<<it->y<<endl; // 返回10,42
// 迭代器、查看
cout<<"迭代器可以找出确定项:"<<(*res.first).x<<"-"<<(*res.first).y<<endl;
// 删除,所有符合条件都会被删除
st.erase(stru(9, 40));
//查看
for (auto it = st.rbegin(); it != st.rend(); it++) //10-40 9-43 9-45 8-40 7-35 6-30 5-25 4-20 3-15 2-10 1-5 0-0
cout<<(*it).x<<"-"<<(*it).y<<" ";
cout<<endl;
// 删除迭代器,只删除特定项
st.erase(res.first);
//查看
for (auto it = st.rbegin(); it != st.rend(); it++) //10-40 9-43 9-45 8-40 7-35 6-30 5-25 4-20 3-15 2-10 1-5 0-0
cout<<(*it).x<<"-"<<(*it).y<<" ";
cout<<endl;
}
从运行结果可以看出,find和erase都失效了,所以需要通过保存迭代器去查找和删除