C++ map, unordered_map

map

低层数据结构:红黑树

基本用法:

#include <iostream>
#include <map>
using namespace std;

int main()
{
    map<char, int> mymap;
    mymap['a'] = 0; //插入数据
    mymap['b'] = 1;
    mymap['c'] = 2;
    map<char, int>::iterator it;
    //遍历
    for(it = mymap.begin(); it!=mymap.end(); it++)
    {
        cout<<it->first<<" "<<it->second<<endl;
    }
    //查找
    it = mymap.find('c');
    if(it == mymap.end())
        cout<<"Not find"<<endl;
    else
        cout<<it->first<<" "<<it->second<<endl;
    return 0;
}

 

unordered_map

底层数据结构:哈希表

#include <iostream>
#include <unordered_map>
using namespace std;

int main()
{
    unordered_map<char, int> mymap;
    mymap['a'] = 0; //插入数据
    mymap['b'] = 1;
    mymap['c'] = 2;
    unordered_map<char, int>::iterator it;
    //遍历
    for(it = mymap.begin(); it!=mymap.end(); it++)
    {
        cout<<it->first<<" "<<it->second<<endl;
    }
    //查找
    it = mymap.find('c');
    if(it == mymap.end())
        cout<<"Not find"<<endl;
    else
        cout<<it->first<<" "<<it->second<<endl;
    return 0;
}

 

posted @ 2019-08-13 22:31  xd_xumaomao  阅读(179)  评论(0编辑  收藏  举报