C++ set容器插入结构体类型的数据
因为插入的类型是自定义的,不是基本类型(基本类型有默认的排序准则),因此需要重载 < 运算符。(相当于给自定义类型一个排序准则)。
e.g. :
-
#include<iostream>
-
#include<set>
-
using namespace std;
-
struct aa{
-
int b;
-
friend bool operator < (const aa& n1, const aa& n2)
-
{
-
return n1. b < n2. b;
-
}
-
};
-
int main()
-
{
-
aa y;
-
y.b = 1;
-
set<aa> uu;
-
uu.insert(y);
-
set<aa>::iterator it = uu.begin();
-
cout<<(*it).b<<endl;
-
return 0;
-
}