C++ map 的使用
生活随笔
收集整理的這篇文章主要介紹了
C++ map 的使用
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
map 簡介
C++ 中 map 對象按順序存儲一組值,其中每個元素與一個檢索關鍵字關聯,
map 的形式 key -- value , 里面的key 是不允許重復的.
map 同樣也是STL中的模板使用的時候 需要先引入 #include?<map>
#include <iostream>
#include <string>
using namespace std;
#include <map>int main()
{// 創建一個空的mapmap<int, string> a;// 插入值使用value_typea.insert(map<int, string>::value_type(1, "張三"));a.insert(map<int, string>::value_type(2, "李四"));a.insert(map<int, string>::value_type(3, "王二"));// 插入值使用paira.insert(pair<int, string>(4, "趙括"));// 使用數組插入a[5] = "張飛";a.insert(map<int, string>::value_type(3, "李白")); // 不允許key重復,無法插入cout << a.size() << endl; // 不允許key重復,打印結果為 5// 遍歷map map<int, string>::iterator it;for (it = a.begin(); it != a.end(); it++){cout << (*it).first << endl;cout << (*it).second << endl;}
}
map 方法說明
| 函數 | 說明 |
| begin | 返回指向map頭部的迭代器 |
| end | 返回指向map末尾的迭代器 |
| empty | 判斷map是否為空,為空返回true |
| size | 返回map中元素的個數 |
| at | 訪問元素 |
| operator[] | 訪問元素 |
| insert | 插入元素 |
| clear | 清空map |
| swap | 交換兩個map |
| find | 查找一個元素 |
| earse | 刪除一個元素 |
| rbegin | 返回反向迭代器以反向開始 |
| rend | 將反向迭代器返回到反向結束 |
| cbegin | 將常量迭代器返回到開頭 |
| cend | 返回常量迭代器結束 |
| crbegin | 返回const_reverse_迭代器以反轉開始 |
| equal_range | 返回特殊條目的迭代器對 |
| lower_bound | ?將迭代器返回到下限 |
| ??upper_bound ????????? | 將迭代器返回到上限 |
| value_comp() | ?返回比較元素value的函數 |
demo 練習
#include <iostream>
#include <string>
using namespace std;
#include <map>int main()
{// 聲明一個setmap<int, string> imap;// 獲取默認set的sizecout << imap.size() << endl;// 插入值使用value_typeimap.insert(map<int, string>::value_type(1, "張三"));imap.insert(map<int, string>::value_type(2, "李四"));imap.insert(map<int, string>::value_type(3, "王二"));// 插入值使用pairimap.insert(pair<int, string>(4, "趙括"));// 使用數組插入imap[5] = "張飛";// 獲取map sizecout << imap.size() << endl;// 遍歷mapmap<int, string>::iterator it;for (it = imap.begin(); it != imap.end(); it++){cout << (*it).first << endl;cout << (*it).second << endl;}//第二個map的value值cout << imap.at(2) << endl;// map 判空if (imap.empty()){cout << "map為空" << endl;}else{cout << "map不為空" << endl;}// 清空mapimap.clear();return 0;
}
總結
以上是生活随笔為你收集整理的C++ map 的使用的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 明代帝王像画是谁画的啊?
- 下一篇: C++ multimap 的使用