STL——map、multimap、unordered__map

map(映射)

map会以键从小到大的顺序自动排序

1、头文件
#include<map>
using namespace std;

2、定义
map<string,int>mp;//字符串到整型的映射//char 数组不能作为键值
map<set<int>,string>mp;

3、访问
例如:map<char,int>mp;的访问
(1)下标访问…………………………………………直接使用mp['c']来访问它对应的整数
(2)通过迭代器访问……………………………it->frist访问键,it->second访问值
定义it:map<char,int>::iterator it;


4、常用函数(见表格)

5、示例(见代码)

6、用途:需要去重但不方便开数组的情况
(1)需要建立字符(或字符串)与整数(或其他基本类型)之间的映射的题目
(2)判断大整数或者其他类型数据是否存在的题目,可以把map当bool数用
基本操作 复杂度
find() find(key)返回键为key的迭代器 O(logN)
erase() erase(it)删除迭代器为it的元素 O(1)
erase(key),key为欲删除映射的键 O(logN)
erase(frist,last)即删除[frist,last)内的所有元素 O(last-frist)
size() 返回map中元素的个数 O(1)
clear() 清空所有元素 O(N)
其他
empty() 如果map为空,返回true
count() 返回某个值元素的个数
lower_bound() lower_bound(key) 返回指向键值大于(或等于)key的第一个元素的迭代器
upper_bound() 返回大于某个键值元素的迭代器
swap() 交换两个map

map用法示例:

map构造方式

#include<bits/stdc++.h>
//#include<map>
using namespace std;
map<string,int>mp;//类似于字典
map<string,int>::iterator it;//每个string 对应一个int
int main()
{
    mp["a"]=12;
    mp["po"]=13;
    mp["cc"]=13;
    mp["cc"]=16;
    mp["dc"]=16;//排序并且去重
    mp.insert(make_pair("hhh",89));
    for(it=mp.begin();it!=mp.end();it++)//遍历
    {
        cout<<(it->first)<<" "<<(it->second)<<endl;
    }
}

map的一些函数

#include<bits/stdc++.h>
//#include<map>
using namespace std;
map<string,int>mp;//类似于字典
map<string,int>::iterator it;//每个string 对应一个int
int main()
{
    mp["a"]=12;
    mp["po"]=13;
    mp["cc"]=13;
    mp["cc"]=16;
    mp["dc"]=16;//排序并且去重
    mp.insert(make_pair("hhh",89));
    cout<<mp.size()<<endl;
    mp.erase("cc");//删
    cout<<mp.size()<<endl;
    cout<<mp.count("po")<<endl;
    cout<<((mp.find("a"))->second);//mp.find("a")返回a的迭代器
    mp.clear();
}

multimap的简单使用

#include<bits/stdc++.h>
//#include<map>乱搞了一个就是字典中的一个可以对应多个,
 
using namespace std;
struct tem1{
int x,y,z;
tem1(){}
tem1(int x,int y,int z):x(x),y(y),z(z){}
friend operator <(const tem1 &a,const tem1 &b)
{
    return a.x<b.x;
}
 
};
struct tem2{
int u,v;
tem2(){}
tem2(int x,int y){u=x,v=y;}
 
};
multimap<tem1,tem2>mp;
multimap<tem1,tem2>::iterator it;
int main()
{
    mp.insert(make_pair(tem1(1,1,1),tem2(1,1)));//只能insert
    mp.insert(make_pair(tem1(1,1,1),tem2(3,6)));
    mp.insert(make_pair(tem1(9,8,5),tem2(1,1)));
    mp.insert(make_pair(tem1(6,1,1),tem2(1,1)));
    for(it=mp.begin();it!=mp.end();it++)
    {
       printf("%d",(*it).first.x);
        printf("\n");
    }
}

unordered__map的简单例子

以散列代替map内部的红黑树实现,比map快得多

#include<bits/stdc++.h>
//#include<map>
using namespace std;
unordered_map<string,int>mp;//类似于字典
unordered_map<string,int>::iterator it;//每个string 对应一个int
int main()
{
    mp["a"]=12;
    mp["po"]=13;
    mp["cc"]=65;
    mp["cc"]=16;
    mp["dc"]=16;//排序并且去重
    mp.insert(make_pair("hhh",89));
 
    cout<<mp["cc"]<<endl;//如果是map需要o(log(n))  unordered__map只要o(1)
}

发布了52 篇原创文章 · 获赞 26 · 访问量 3175

猜你喜欢

转载自blog.csdn.net/qq_43803508/article/details/99120783