从STL关联容器的比较说起

1240阅读 0评论2016-06-20 sytpb
分类:C/C++

定义一个集合

std::set s1
std::set s3;

一、第一种比较函数默认是Less,这是STL内置函数子类,返回函数子(仿函数/函数对象)

如果是用户自定义类型 std::set<IKey> s;

IKey需要重载(override)  operator<

点击(此处)折叠或打开

  1. typedef struct IKey
  2. {
  3.     char code[8];
  4.     long flag;
  5.     struct IKey():flag(0)
  6.     {
  7.         memset(code,0,sizeof(code));
  8.     }

  9.     bool operator<(IKey const& rhs)const
  10.     {
  11.         if(memcmp(code,rhs.code,sizeof(code)) < 0 ||
  12.             (memcmp(code,rhs.code,sizeof(code)) == 0 && flag < rhs.flag))
  13.             return true;
  14.         return false;
  15.     }
  16. }KEY;

二、第二种是要指定自定义的函数子类COMPARE。这里有二种方式。

1:利用STL内置的一些函数子类 less  less_equalequal not_equal greater_equal greater

std::setgreater > s1;
如果是自定义类型,不同的函数子类要重载不同的操作符, 这里重载的是 operator>(IKey const& rhs)const

2: 自定义函数子类作为判别式

std::set s2;

点击(此处)折叠或打开

  1. struct WCompare
  2. {
  3.    public:
  4.    bool operator()(const WCompare& lhs, const WCompare& rhs) const
  5.    {
  6.       return lhs.a < rhs.b;
  7.    }
  8.    private:
  9.    int a;

  10. }
这里需要遵守二个重要规则 Effective STL 38 条值传递原则设计函数子类 和 39条判别式“纯函数

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:: s ,就是operator>
(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 函数



上一篇:C++ 11 学习之 -- std::bind总结
下一篇:没有了