c++中set存储自定义数据类型使用find方法时的疑惑
- 在set中存储了一个简单的坐标类,仅包含两个整数数据x和y
- 而当想要去在set中查找某一个坐标时,发现该坐标并未存在,但却查找成功
- 最后发现其原因是对于想要查找的对象(x,y),该组数据虽然并未在set中存储,但set存储的某组数据中包含了x或y其中的一个,最后使用find方法返回的迭代器指向了(x,z)或(y,z)
对于这一问题,想要请教大家造成这一结果的原因,以及有没有方法可以准确在set中查询(x,y)这组数据,而不是(x,z)或(y,z)
#include<set>
#include<iostream>
#include<algorithm>
using namespace std;
#if 1
class Pos
{
public:
Pos() {};
Pos(int x, int y)
{
this->x = x;
this->y = y;
}
int x, y;
};
class Compare
{
public:
bool operator()(const Pos& p1, const Pos& p2) const
{
return p1.x < p2.x;
}
};
int main()
{
set<Pos, Compare>big;
big.insert({ 0,0 });
big.insert({ 1,1 });
big.insert({ 2,2 });
int x=big.count(Pos(1,100)); //在set中寻找(1,100)这组数据
cout << x << endl;
if (big.find(Pos{1,100})!=big.end()) //发现并未在set中插入(1,100)这组数据,却可以在set中查找到
cout << "find success" << endl;
auto it = big.find(Pos(1,100)); //发现当查找(1,100)时只找到了其中的1一个数据,并不完全符合想要在set中查找对象的两个数据
if(it!=big.end()) //其最后的查找结果为(1,1)这组数据
cout << it->x << " " << it->y << endl;
for (auto e : big)
cout << e.x << " " << e.y << endl;
system("pause");
}
#endif