
一、算法题常用1.1 CSTL中哈希表std::unordered_map和std::unordered_multimapunordered_map和unordered_multimap区别在与mult的值可以重复。方法insert、erase、size、count统计出现次数其他操作unordered_mapstring, vectorstring strsMap;该怎么添加元素for(inti0;istrs.size();i){string tempstrs[i];sort(temp.begin(),temp.end());//重点strsMap[temp].push_back(strs[i]);}#includeiostream#includeunordered_mapintmain(){std::unordered_mapstd::string,intageMap;// 插入元素ageMap[Alice]30;ageMap[Bob]25;ageMap[Charlie]35;// 访问元素std::coutAlices age: ageMap[Alice]std::endl;// 查找元素autosearchageMap.find(Bob);if(search!ageMap.end()){std::coutBobs age: search-secondstd::endl;}return0;}#includeiostream#includeunordered_map// 注意这里用的是 unordered_map 的头文件因为 multimap 也包含在里面intmain(){std::unordered_multimapstd::string,intscores;// 插入元素scores.insert({Alice,90});scores.insert({Bob,85});scores.insert({Alice,95});// Alice 有两个分数// 访问元素演示如何遍历一个键的所有值autorangescores.equal_range(Alice);// 获取所有键为 Alice 的元素的范围for(std::unordered_multimapstd::string,int::iterator itrange.first;it!range.second;it){std::coutAlices score: it-secondstd::endl;}return0;}1.2 unordered_set和unordered_map区别unordered_set只存【键 key】不存值用来去重 快速查找元素是否存在 。unordered_map存【键值对 key-value】用来通过键快速查值 。#includeunordered_setusingnamespacestd;intmain(){unordered_setints;// 插入s.insert(10);s.insert(20);s.insert(10);// 重复自动忽略去重// 查找判断 10 是否存在if(s.count(10)){// 存在}// 遍历只有 key没有 valuefor(autox:s){// x 就是存储的元素}}1.3对于算法题中的字符串问题可以先考虑对字符串排序例如49. 字母异位词分组