c++ unordered_map 哈希表使用
阿新 • • 發佈:2018-05-19
tor 元素 clu ket red bsp second fir tree
C++中的 unordered_map使用時通過鍵值對進行插入,並通過find(key)進行尋找鍵值是否存在。
//iterator find (key) : 找到則返回對應鍵值得叠代器 //沒有找到則返回unordered_map::end. // unordered_map::find if ( got == mymap.end() ) std::cout << "not found"; else std::cout << got->first << " is " << got->second;
不能插入重復元素,即具有同樣鍵值(key)的元素。
#include <iostream> #include <string> #include <unordered_map> using namespace std; int main() { unordered_map<string, string> mymap = { {"house", "maison"}, {"apple", "pomme"}, {"apple", "pomme"}, {"apple", "pomme1"}, {"tree", "arbre"}, {"book", "livre"}, {"door", "porte"}, {"grapefruit", "pamplemousse"} }; unsigned n = mymap.bucket_count(); cout << "mymap has " << n << "buckets.\n"; for(unsigned i = 0; i < n; i++) { cout << "bucket #" << i << "contains: "; for(auto it = mymap.begin(i); it != mymap.end(i); ++it) { cout << "[" << it->first << ":" << it->second << "]"; } cout << "\n"; } return 0; } /* 輸出 *mymap has 11buckets. *bucket #0contains: *bucket #1contains: [book:livre] *bucket #2contains: [grapefruit:pamplemousse] *bucket #3contains: [house:maison] *bucket #4contains: *bucket #5contains: *bucket #6contains: *bucket #7contains: *bucket #8contains: *bucket #9contains: [apple:pomme] *bucket #10contains: [door:porte][tree:arbre] */
c++ unordered_map 哈希表使用