intmain(){ // 创建一个 unordered_map,键为 int,值为 string std::unordered_map<int, std::string>myMap; // 插入一些键值对 myMap[1]="one"; myMap[2]="two"; myMap[3]="three"; // 打印所有元素 for(constauto&pair:myMap){
(2)使用范围for循环遍历unordered_map,这种方式更加简洁。使用const auto& pair来捕获每个键值对,并使用pair.first和pair.second分别访问键和值。 1 #include <iostream> 2 #include <unordered_map> 3 int main() { 4 std::unordered_map<int, std::string> mymap = {{1, "one"}, {2, "two"}, {...
#include <iostream> #include <string> #include <random> #include <unordered_map> #include <windows.h> using namespace std; using std::string; using std::random_device; using std::default_random_engine; string StrRand(int length) { char tmp; string buffer; random_device rd; default_rando...
头文件:include <unordered_map> 下面的代码中都包含了std:using namespace std;,也包含了头文件#include<string> 创建map对象 代码语言:javascript 代码运行次数:0 运行 AI代码解释 typedef unordered_map<string, int> strIntMap; strIntMap map1; strIntMap map2({ {"Tom", 80}, {"Lucy...
1.3 unordered_map unordered_map容器的底层实现是Hash Table,元素乱序存储,但增删改查效率极高,复杂度均为 O(1) 代码语言:javascript 代码运行次数:0 运行 AI代码解释 unordered_map<string, int> unMap; cout << "unordered_map中的key值无序(底层哈希表实现):" << endl; unMap["B"] = 22; unMap["A...
std::pair<std::map<int, std::string>::iterator,bool> retPair; retPair = studentMap.insert(std::pair<int, std::string>(15,"Bob"));for(autoi:studentMap) { cout<<i.first<<" "<<i.second; cout<<endl; } std::map<int, std::string>::iterator itor = studentMap.find(7);if(it...
当key不是int类型而是string时,就不能取余数了。那该怎么办呢? 这里需要用到仿函数,如下图: 当key可以强转成整形时(比如负数,指针等),用缺省的仿函数即可。当key是string这种不能强转成整形的类型时,就要手动写一个转换成整形的仿函数。上方是取string的第一个字符进行返回。同时也要手动传入这个仿函数。
intmain() { unordered_map<int,string>um; um.insert(pair<int,string>(1,"one"));//一般插入 um[3]="three";//数组的形式,如果存在就修改,否则插入 um.insert(pair<int,string>(2,"two")); um[2]="twotwo";//修改 for(autoit=um.begin();it!=um.end();++it)//begin,end,迭代器 ...
#include <iostream>#include <unordered_map>int main() {std::unordered_map<int, std::string> map;// 设置一些键值对map[1] = "one";map[2] = "two";map[3] = "three";// 获取当前负载因子float lf = map.load_factor();std::cout << "Load Factor: " << lf << std::endl;return ...
unordered_map<string,int>word_count;//空的 stringword; while(cin>>word) { ++word_count[word]; } for(constauto&w:word_count) { cout<<w.first<<" occurs "<<w.second<< ((w.second>1)?" times":" time")<<endl; } 1. 2. ...