Cpp浅析系列-STL之map( 四 )

追查源码 , 我发现他是用的find方法 , 将结果跟尾迭代器比较 , 如果不等于尾迭代器就是找到了 , 返回1;反之就是没找到 , 返回0 。
    find(const _Key& __k) const    {      const_iterator __j = _M_lower_bound(_M_begin(), _M_end(), __k);      return (__j == end()       || _M_impl._M_key_compare(__k,     _S_key(__j._M_node))) ? end() : __j;    }find获取元素迭代器/* * 用find函数寻找元素 ,  * */void find2(set<int> s ){    if (s.find(4)!= s.end() ) {        cout << "元素4存在"<<endl;    }else{        cout << "元素4不存在";    }    if (s.find(8)!= s.end() ) {        cout << "元素8存在"<<endl;    }else{        cout << "元素8不存在";    }}而底层是调用的不带const标的find函数 , 函数体是一样的!而其中的核心逻辑就是用_M_lower_bound函数查找来确定位置 。
    _M_lower_bound(_Link_type __x, _Base_ptr __y, const _Key &__k){        while (__x != 0) {            if (!_M_impl._M_key_compare(_S_key(__x), __k))                __y = __x, __x = _S_left(__x);            else                __x = _S_right(__x);        }        return iterator(__y);    }比较函数key排序map中默认就是使用key排序的 , 自动按照key的大小 , 增序存储 , 这也是作为key的类型必须能够进行 < 运算比
较的原因 。
首先看一眼map模板的定义 , 重点看下第三个参数:class Compare = less<Key>  。
template < class Key ,  class T ,  class Compare = less<Key> ,            class Allocator = allocator<pair<const Key , T> > > class map;与less相对的还有greater , 都是STL里面的一个函数对象 , 那么什么是函数对象呢?
函数对象:即调用操作符的类 , 其对象常称为函数对象(function object) , 它们是行为类似函数的对象 。表现出一个函数的特征 , 就是通过“对象名+(参数列表)”的方式使用一个 类 , 其实质是对operator()操作符的重载 。
具体的例子可以去看另一篇文章:Cpp浅析系列-STL之set , 这里就不赘述了 。
value排序逻辑上是先转为vector数组 , 接着将数组用指定的规则重新排序得到排序好的结果 。至于是否用排序好的数组去转换为map对象则是看要求了 。
bool Special(pair<string, int> a, pair<string, int> b) {    return a.second < b.second;//从小到大排序}void specialCompare() {    // 初始map集合    map<string, int> m;    m["a"] = 2;    m["b"] = 3;    m["c"] = 1;    // 转为vector集合    vector<pair<string, int> > demo(m.begin(), m.end());    for (auto it = demo.begin(); it != demo.end(); ++it) {        cout << (*it).first << " " << (*it).second << endl;    }    cout << endl;    // 排序后查看效果    sort(demo.begin(), demo.end(), Special);    for (auto it = demo.begin(); it != demo.end(); ++it) {        cout << (*it).first << " " << (*it).second << endl;    }    cout << endl;    // 转换为新的map集合 , 区别就是前后类型反了 。    map<int, string> m2;    for (vector<pair<string, int> >::iterator it = demo.begin(); it != demo.end(); ++it){        m2[(*it).second]=(*it).first;    }    map<int, string>::iterator iter;    for (iter = m2.begin(); iter != m2.end(); iter++) {        cout << iter->first << ' ' << iter->second << endl;    }}//a 2// b 3// c 1//// c 1// a 2// b 3//// 1 c// 2 a// 3 b


推荐阅读