map
优点: 有序性,这是map结构最大的优点,其元素的有序性在很多 应用中都会简化很多的操作树,内部实现一个树使得map的很多操作在logn的时间复杂度下就可以实现,因此效率非常的高
缺点: 空间占用率高,因为map内部实现了树,虽然提高了运行效率,但是因为每一个节点都需要额外保存父节点,使得每一个节点都占用大量的空间
适用处: 对于那些有顺序要求的问题,用map会更高效一些
map构造函数
map<key, value> map;
//map的基本构造函数
map<string , int >strMap;
map<int ,string >intMap;
map<string, char>strMap;
map< char ,string>charMap;
map<char ,int>charMap;
map<int ,char >intMap;
map常用函数
- begin()
返回指向map头部的迭代器 - clear()
删除所有元素 - count()
返回指定元素出现的次数 - empty()
如果map为空则返回true - end()
返回指向map末尾的迭代器 - equal_range()
返回特殊条目的迭代器对 - erase()
删除一个元素 - find()
查找一个元素 - get_allocator()
返回map的配置器 - insert()
插入元素 - key_comp()
返回比较元素key的函数 - lower_bound()
返回键值>=给定元素的第一个位置 - max_size()
返回可以容纳的最大元素个数 - rbegin()
返回一个指向map尾部的逆向迭代器 - rend()
返回一个指向map头部的逆向迭代器 - size()
返回map中元素的个数 - swap()
交换两个map - upper_bound()
返回键值>给定元素的第一个位置 - value_comp()
返回比较元素value的函数
实例
#include <iostream>
#include "string.h"
#include "stdio.h"
#include<map>
using namespace std;
int main(){
map<string,int> strMap; //以string为键值,以int为实值
strMap[string("jjhou")] = 1;
strMap[string("jerry")] = 2;
strMap[string("jason")] = 3;
strMap[string("jimmy")] = 4;
pair<string,int> value(string("david"),5);
strMap.insert(value);//插入新元素
map<string,int>::iterator strmap_iter = strMap.begin();
for(;strmap_iter !=strMap.end();strmap_iter++)
{
cout<<strmap_iter->first<<' '<<strmap_iter->second<<endl;
}
cout<<endl;
int number = strMap[string("jjhou")];
cout<<number<<endl;
cout<<endl;
//查找元素
map<string,int>::iterator iter1;
//面对关联式容器,应该使用其所提供的find函数来搜索元素,会比使用STL算法find()更有效率。因为STL算法find()只是循环搜索。
iter1 = strMap.find(string("mchen"));
if(iter1 == strMap.end())
cout<<"mchen no fount"<<endl;
cout<<endl;
iter1 = strMap.find(string("jerry"));
if(iter1 != strMap.end())
cout<<"jerry fount"<<endl;
cout<<endl;
//修改实值,键值不可修改
iter1->second = 9; //可以通过map迭代器修改“value”(not key)
int number1 = strMap[string("jerry")];
cout<<number1<<endl;
//删除元素
map<string,int>::iterator strmap_iter1 = strMap.begin();
for(;strmap_iter1 !=strMap.end();strmap_iter1++)
{
cout<<strmap_iter1->first<<' '<<strmap_iter1->second<<endl;
}
cout<<endl;
strMap.erase(iter1);//删除一个条目
strMap.erase(string("jason"));//根据键值删除
map<string,int>::iterator strmap_iter2 = strMap.begin();
for(;strmap_iter2 !=strMap.end();strmap_iter2++)
{
cout<<strmap_iter2->first<<' '<<strmap_iter2->second<<endl;
}
}
unordered_map
优点: 因为内部实现了哈希表,因此其查找速度非常的快
缺点: 哈希表的建立比较耗费时间
适用处: 对于查找问题,unordered_map会更加高效一些,因此遇到查找问题,常会考虑一下用unordered_map
unordered_map构造函数
unordered_map<key, value> ump;
unordered_map常用函数
- 插入数据
ump.insert(make_pair(key, value));
或
ump.insert(Map::value_type(key, value));
- 数值查找
if (umap.find(key) != umap.end())
cout << key << "found "<<endl;
else
cout << key << "not found " << endl;
或
ump.count(key) != 0
- 数值遍历
unordered_map<key, value>::iterator i;
for (i=ump.begin();i!=ump.end();i++)
cout<<i->first<<" "<<i->second<<endl;
- 删除
//根据key删除,如果没找到n=0
auto n = ump.erase("test");
- 修改value值
auto it = ump.find(key);
if(it != ump.end())
it->second = new_value;