C++中使用哈希表(unordered_map)的一些常用操作方法
1.建立基本數(shù)據(jù)類型的哈希表
unordered_map<int,int> m; //<string,string>,<char,char>
2.向哈希表中添加元素
1).insert 函數(shù)
m.insert(pair<int,int>(1, 10)); m.insert(pair<int,int>(2, 20));
2).用數(shù)組方法直接添加
m[3]=30; m[4]=40;
3.成員函數(shù)
begin(),end()函數(shù)
m.begin() //指向哈希表的第一個容器 m.end() //指向哈希表的最后一個容器,實(shí)則超出了哈希表的范圍,為空
find()查找函數(shù)
m.find(2) //查找key為2的鍵值對是否存在 ,若沒找到則返回m.end() if(m.find(2)!=m.end()) //判斷找到了key為2的鍵值對
count() 查找函數(shù)
查找哈希表中key為3的鍵值對,返回其數(shù)量,為1,則找到,若沒找到則返回0
m.count(3) //返回 1 m.count(5) //返回0
size()函數(shù)
m.size() //返回哈希表的大小
empty()函數(shù)
m.empty() //判斷哈希表是否為空,返回值為true/false
clear()函數(shù)
m.clear() //清空哈希表
swap()函數(shù)
交換兩個哈希表中的元素,整個哈希表的鍵值對全部都交換過去
unordered_map<int,int> m1; unordered_map<int,int> m2; m1.swap(m2); swap(m1,m2);
哈希表的遍歷
第一種遍歷
unordered_map<int, int> count; for (auto p : count) { int front = p.first; //key int end = p.second; //value }
第二種遍歷
unordered_map<int, int> count; for(auto it=m.begin();it!=m.end();it++) { int front = it->first; //key int end = it->second; //value }
補(bǔ)充:實(shí)際應(yīng)用
LeetCode的242題:有效的字母異位詞
題目描述:
給定兩個字符串 s 和 t ,編寫一個函數(shù)來判斷 t 是否是 s 的字母異位詞。
示例 1:
輸入: s = "anagram", t = "nagaram"
輸出: true
示例 2:輸入: s = "rat", t = "car"
輸出: false
說明:
你可以假設(shè)字符串只包含小寫字母。來源:力扣(LeetCode)
鏈接:https://leetcode-cn.com/problems/valid-anagram
具體的分析可以去看LeetCode上面的優(yōu)質(zhì)解答,那上面的最高贊,或者關(guān)注的人比較多的答案基本都是很優(yōu)秀的解答和分析。這個問題的解法其中一個就是使用了unordered_map進(jìn)行解決的:
class Solution { public: bool isAnagram(string s, string t) { if (s.length() != t.length()) { return false; } unordered_map<char, int> umap; for (int i = 0; i < s.size(); ++i) { umap[s[i]]++; umap[t[i]]--; } for (auto ch : umap) { if (ch.second != 0) { return false; } } return true; } };
總結(jié)
到此這篇關(guān)于C++中使用哈希表(unordered_map)的常用操作的文章就介紹到這了,更多相關(guān)C++使用哈希表(unordered_map)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
詳解C++?STL模擬實(shí)現(xiàn)vector
這篇文章主要為大家詳細(xì)介紹了C++如何模擬實(shí)現(xiàn)STL容器vector,文中的示例代碼講解詳細(xì),對我們學(xué)習(xí)C++有一定幫助,需要的可以參考一下2023-01-01C++ 動態(tài)數(shù)組模版類Vector實(shí)例詳解
這篇文章主要為大家詳細(xì)介紹了C++動態(tài)數(shù)組模版類Vector實(shí)例,文中示例代碼介紹的非常詳細(xì),具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下,希望能夠給你帶來幫助2022-02-02

C語言經(jīng)典算法例題求100-999之間的“水仙花數(shù)”

Qt編寫地圖實(shí)現(xiàn)海量點(diǎn)位標(biāo)注

基于linux下C開發(fā)中的幾點(diǎn)技術(shù)經(jīng)驗(yàn)總結(jié)

C/C++題解LeetCode1295統(tǒng)計(jì)位數(shù)為偶數(shù)的數(shù)字