标签:return else ++ map contains names cout find iterator
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] */
标签:return else ++ map contains names cout find iterator
原文地址:https://www.cnblogs.com/Shinered/p/9061696.html