map类

特点

一:map类

    1:内部时红黑树,所以自动排序,无论是插入还是删除,查找都是o(logn),不允许键值重复。

    2:存放<key, value>键值对的数据结构,至于排序方式时从小倒是还是从大到小取决与less还是greater

      template <class T> struct less : binary_function <T,T,bool> {   

               bool operator() (const T& x, const T& y) const 

               {return x<y;}  

       };  less时从小到大

     map指定less作为其默认比较函数(对象)

     当然也可手动指定排序方式:map<string, int, greater<string> > name_score_map;  //从大到小

    3:自定义比较函数:

         现在知道如何为map指定Compare类了,如果我们想自己写一个compare的类,让map按照我们想要的顺序来存储,比如,按照学生姓名的长短排序进行存储,那该怎么做呢?

        其实很简单,只要我们自己写一个函数对象,实现想要的逻辑,定义map的时候把Compare指定为我们自己编写的这个就ok啦。

         struct CmpByKeyLength { 

               bool operator()(const string& k1, const string& k2) {

                      return k1.length() < k2.length();  

                 }  

          }

           //用法:  map<string, int, CmpByKeyLength> name_score_map;  

对外接口:

        1:

             map支持常见的迭代器接口,例如begin(),end(),rbegin(),rend(). 

            empty()        判断map是否为空。为空的话返回真。

            size()           返回map的长度

            pair<key_type,value_type>;

            //h.insert(make_pair(1,2))        //cout<<p.first<<' '<<p.second<<endl;pair对通过first和second访问.

        2:   map<int,int > :: iterator//迭代器

例子:

#include <map>

#include <iostream>

using namespace std; 

typedef pair<int,int> int_pair;

map<int,int>::iterator itr1;

map<int,int> m1; //默认升序,从小到大

m1[1] = 10; 

m1[2] = 20;

m1[3] = 30;

//输出结果10 20 30,有换行

for (itr1 = m1.begin(); itr1 != m1.end(); ++itr1)

{

    cout << itr1->second << endl;

}

二:hash_map

                   底层是hash_table,查找效率可观,没有自动排序,可理解为数组+链表  ,其中redis中的Redis sorted set的内部使用HashMap和跳跃表(SkipList)来保证数据的存储和有序。比较高效

                   跳跃表:地铁。

posted @ 2018-05-03 00:19  WorldsCollide  阅读(65)  评论(0)    收藏  举报