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() //逆迭代器
