1. find()函數ios
C++中的 unordered_map使用時經過鍵值對進行插入,並經過find(key)進行尋找鍵值是否存在。app
//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] */
2. 本身寫的一個類測試unordered_map的使用,感受鍵值映射的value值好像沒什麼用。測試
/*typedef pair<const Key, T> value_type; *unordered_map<Key, T>::iterator it; (*it).first; | it->first //the key value *(*it).second;| it->second //the mapped value */ #include <iostream> #include <fstream> #include <sstream> #include <unordered_map> #include <string> #include <ctime> using namespace std; /* compute the number of target value t int the interval[-10000,10000] * such that distinct number x, y int the input file that * satisfy x+y=t. * */ class TwoSum { public: TwoSum() { get_data(); for(long long x = -10000; x <= 10000; x++) { calc_times(x); } } /************讀入數據 ***********/ void get_data() { ifstream fin("algo1-programming_prob-2sum.txt"); string line; long long count = 0; stringstream stream; while(getline(fin,line)) { long long data; stream.clear(); stream << line; stream >> data; /* 插入鍵值對,感受映射的value有時候沒有什麼用 */ map.insert(make_pair( data,count )); count ++; } } /****************計算x+y=sum對的個數***************/ void calc_times(long long sum) { for(auto &x : map) { unordered_map<long long, long long >::iterator got = map.find(sum-(x.first)); if( ( got != map.end() ) && (sum-x.first != x.first) ) { totalSum ++; } } } public: unordered_map<long long , long long > map; //hashtable long long totalSum = 0; }; int main() { clock_t start, end; start = clock(); TwoSum twosum; end = clock(); cout << twosum.totalSum << endl; cout << "running time:" << (double)(end-start) / CLOCKS_PER_SEC << "s" << endl; return 0; }