std::set s1
std::set s3;
一、第一种比较函数默认是Less,这是STL内置函数子类,返回函数子(仿函数/函数对象)
如果是用户自定义类型 std::set<IKey> s;
IKey需要重载(override) operator<
点击(此处)折叠或打开
-
typedef struct IKey
-
{
-
char code[8];
-
long flag;
-
struct IKey():flag(0)
-
{
-
memset(code,0,sizeof(code));
-
}
-
-
bool operator<(IKey const& rhs)const
-
{
-
if(memcmp(code,rhs.code,sizeof(code)) < 0 ||
-
(memcmp(code,rhs.code,sizeof(code)) == 0 && flag < rhs.flag))
-
return true;
-
return false;
-
}
- }KEY;
二、第二种是要指定自定义的函数子类COMPARE。这里有二种方式。
1:利用STL内置的一些函数子类 less less_equalequal not_equal greater_equal greater
std::set
如果是自定义类型,不同的函数子类要重载不同的操作符, 这里重载的是 operator>(IKey const& rhs)const
2: 自定义函数子类作为判别式
std::set s2;
点击(此处)折叠或打开
- struct WCompare
-
{
-
public:
-
bool operator()(const WCompare& lhs, const WCompare& rhs) const
-
{
-
return lhs.a < rhs.b;
- }
- private:
- int a;
-
-
}
3:lambda 函数实现
补....
三、等价判断
1:key_comp()(const T& x,const T& y)
当关联容器调用自己的成员函数 insert erase find等时,STL会进行等价判断,注意这里的find 不是std::find 这二者不一样,如Effective STL 44条里提到std::find 是以相等性进行判断,关联容器成员函数 find是以等价性进行判断。
这里要提到一个内置函数子 key_comp()(const T&x,const T&y)
它会指向类型实现的比较函数,针对上面所提情况分别是:
(a) std:: s 默认比较,就是operator<
(b) std::
(c) std::set s2;就是 bool operator()(const WCompare& lhs, const WCompare& rhs) const
(d) lambda 函数实现
这里有一个重要准则 Effective STL 21条比较函数在等值情况下返回false。false 代表等值二个值没有先后顺序。
2:等价判断公式
! key_comp()(x,y) && ! key_comp(y,x)
如果结果true,说明已存在等价key, 如果false,说明不存在等价的key。 所以播入时,结果为false 才可以insert
四、其他
std::find 相等性判断,调用的是operator==
五、总结
本文涉及几方面
1: equality(相等) equivalence (等价)
2: 函数子数
3: 等价判断
4: 比较函数
5:lambda 函数