set 结构体

C++的设计哲学之一就是使得程序在对待自定义类型时和内置类型必须是一致的(甚至自定义类型的支持更好)。所以,肯定是你程序的问题,如下:
《C++标准程序库》中明确指出:“只要是 assignable、copyable、comparable (根据某个排序准则)的型别T,都可以成为set或multiset的元素型别。”。其中,所谓的comparable指的是less,即可进行<比较。

反之,则不被支持,所以,问题是,你的A是否支持上述三种语义?

看下面的测试代码:
C/C++ code
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
void  test(){
set<A>s;
A a,b,c;
a.str= "shanying" ;a.score=100;
b.str= "shanying" ;b.score=0;
c.str= "baitoudiao" ;c.score=50;
 
A cpy(a);
cout<< "orign:" <<a.str<< ',' <<a.score<<endl;
cout<< "copy:" <<cpy.str<< ',' <<cpy.score<<endl;
 
A assigned;
assigned = a;
cout<< "assigned:" <<assigned.str<< ',' <<assigned.score<<endl;
 
// cout<<"a<b?"<<(a<b?"true":"false")<<endl;       无法通过编译
}


输出:
orign:shanying,100
copy:shanying,100
assigned:shanying,100

所以,A满足assignable以及copyable,但是不满足comparable,所以,它不能用于set容器。为了达到目的,需要做的就是添加一个对operator<的重载。

参考修正后的代码:
C/C++ code
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include <iostream>
#include <string>
#include <set>
using  namespace  std;
struct  A{
string str;
int  score;
};
 
bool  operator<( const  A& lhs,  const  A& rhs) {
     return  lhs.score<rhs.score;
}
 
void  test(){
set<A>s;
A a,b,c;
a.str= "shanying" ;a.score=100;
b.str= "shanying" ;b.score=0;
c.str= "baitoudiao" ;c.score=50;
 
A cpy(a);
cout<< "orign:" <<a.str<< ',' <<a.score<<endl;
cout<< "copy:" <<cpy.str<< ',' <<cpy.score<<endl;
 
A assigned;
assigned = a;
cout<< "assigned:" <<assigned.str<< ',' <<assigned.score<<endl;
 
cout<< "a<b?" <<(a<b? "true" : "false" )<<endl;
 
s.insert(a);
s.insert(b);
s.insert(c);
 
cout<< "size:" <<s.size()<<endl;
}
 
int  main() {
     test();
 
     return  0;
}


编译可通过,输出为:
orign:shanying,100
copy:shanying,100
assigned:shanying,100
a<b?false
size:3
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值