C++ set容器插入结构体类型的数据

因为插入的类型是自定义的,不是基本类型(基本类型有默认的排序准则),因此需要重载 < 运算符。(相当于给自定义类型一个排序准则)。

e.g. :

  1. #include<iostream>
  2. #include<set>
  3. using namespace std;
  4. struct aa{
  5. int b;
  6. friend bool operator < (const aa& n1, const aa& n2)
  7. {
  8. return n1. b < n2. b;
  9. }
  10. };
  11. int main()
  12. {
  13. aa y;
  14. y.b = 1;
  15. set<aa> uu;
  16. uu.insert(y);
  17. set<aa>::iterator it = uu.begin();
  18. cout<<(*it).b<<endl;
  19. return 0;
  20. }



posted @ 2019-09-02 16:00  xjyxp01  阅读(1138)  评论(0编辑  收藏  举报