map和unordered_map使用小结

map和unordered_map

 

unordered_map简介:

 

#include <cstdio>
#include <iostream>
#include <unordered_map>//两个头文件都行
//#include <tr1/unordered_map>
using namespace std;
int main(int argc, char const *argv[]){
  unordered_map<int,int>mp;//创建

  printf("%d\n", mp[100]);//默认为0,注意:此时mp里已有一个元素的key是100,value是0

  mp[12]=1;//简单赋值
  mp[5]=5;

  mp.erase(12);//两种erase方法

  printf("key: 12 -> value: %d\n", mp[12]);

  mp[12]=101;

  unordered_map<int,int>::iterator it;//迭代器
  it = mp.find(5);
  if(it!=mp.end())printf("YES, it's %d\n", *it);
  else printf("NO!\n");

  mp.erase(it);

  printf("key:\n");
  for(auto x: mp){//访问key
    printf("%d\n", x);
  }

  printf("value:\n");
  for(auto x: mp){//访问value
    printf("%d\n", x.second);
  }

  return 0;
}
/*
0
key: 12 -> value: 0
YES, it's 5
key:
12
100
value:
101
0
请按任意键继续. . .
*/

 

 

map简介

map是一类关联式容器,增加和删除节点对迭代器的影响很小。除了对操作节点有影响,对其他的节点没有什么影响。map主要建立了key到value的映射。key和value可以是任意类型。

注意:对于迭代器来说,可以修改实值,而不能修改key。

 

map基本操作:

C++ Maps是一种关联式容器,包含“关键字/值”对
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的函数

 

 

map添加数据:

map<int,int>mp;

未插入数据时,值默认为0:

if(mp[100]==0)cout<<"hello!\n";
map<int ,string> mp; mp.insert(pair<int,string>(1,"hello")); mp.insert(map<int,string>::value_type(w,"world")); mp[3]="haha";


map元素的查找:

find()函数返回一个迭代器指向键值为key的元素,如果没找到就返回指向map尾部的迭代器。        
map<int ,string >::iterator it;
it=maplive.find(110);
if(it==maplive.end())cout<<"Do not find 110!\n";
else cout<<"Find 112!\n";


map的swap的用法
  map中的swap不是一个容器中的元素交换,而是两个容器交换;


map的sort问题:
  map中的元素是自动按key升序排序,所以不能对map用sort函数:

 

 

 

类似的还有set和unordered_map。对了,别忘了multiset和multimap这俩东西。

 set的数据操作

::begin()  //迭代器

::end()      //迭代器

::clear()   //删除set容器中的所有的元素

::empty()    //判断set容器是否为空

::max_size()  //返回set容器可能包含的元素最大个数

::size()    //返回当前set容器中的元素个数

::rbegin   //逆迭代器

::rend()  //逆迭代器

posted @ 2018-05-09 15:22  Cwolf9  阅读(1956)  评论(0编辑  收藏  举报