• [C++]-unordered_map 映射


    unordered_mapmap的区别请点击这里
    本文中的代码跟[C++]-map 映射中的代码仅仅是把定义的map类型数据定义成了unordered_map类型数据。

    代码

    #include<iostream>
    #include<unordered_map>
    #include<string>
    using namespace std;
    
    inline void print_map(unordered_map<string, double> m)
    {
    	/** 此种遍历输出方法也可
    	for(unordered_map<string, double>::iterator it = m.begin(); it != m.end(); ++it) // it指向一个二元组 
    		cout << it->first << ": " << it->second << endl; cout << endl;  
    	*/
    	for(auto x : m)
    		cout << x.first << ": " << x.second << endl; cout << endl;
    }
    
    int main()
    {
    	unordered_map<string, double> mymap;
    	
    	cout << "-----插入------" << endl;
    	mymap.insert(pair<string, double>("xxm", 1.1));
    	mymap.insert(make_pair("mqg", 2.2));
    	mymap.insert(unordered_map<string, double>::value_type("lpp", 3.3)); 
    	mymap["zhx"] = 4.4;
    	print_map(mymap); // 没有排序,按照哈希表从前到后遍历 
    	
    	cout << "-----通过键获取元素值------" << endl;
    	// 直接索引
    	// 通过索引直接获取对应的值,不存在键sjx,则返回double无参构造函数赋值为0 
    	cout << mymap["xxm"] << " " << mymap["sjx"] << endl; 
    	// 由于刚才 mymap["sjx"]语句,现在mymap中多了一个键值对mymap["sjx"]=0 
    	// for循环遍历 
    	print_map(mymap);
    		
    	cout << "----- 判断是否存在某个键------" << endl;
    	unordered_map<string, double>::iterator it1 = mymap.find("xxm"); // 存在,返回对应的迭代器 
    	if(it1 == mymap.end())
    		cout << "不存在该键" << endl;
    	else
    		cout << it1->second << endl; 
    	unordered_map<string, double>::iterator it2 = mymap.find("xxxxm"); // 不存在,返回mymap.end() 
    	if(it2 == mymap.end())
    		cout << "不存在该键" << endl;
    	else
    		cout << it2->second << endl; 
    	cout << endl; 
    	
    	cout << "-----删除------" << endl;
    	mymap.erase("xxm"); // 删除键为xxm的键值对 
    	mymap.erase(++mymap.begin()) ; // 删除第二个元素 
    	print_map(mymap);
    	mymap.erase(mymap.begin(), mymap.end()); // 删除[mymap.begin(), mymap.end())区间的元素
    	if(mymap.empty()) cout << "mymap已空" << endl;
    	mymap.clear(); // 直接将映射内容全部清空
    }
    

    运行结果

    -----插入------
    zhx: 4.4
    lpp: 3.3
    mqg: 2.2
    xxm: 1.1
    
    -----通过键获取元素值------
    1.1 0
    sjx: 0
    zhx: 4.4
    lpp: 3.3
    mqg: 2.2
    xxm: 1.1
    
    ----- 判断是否存在某个键------
    1.1
    不存在该键
    
    -----删除------
    sjx: 0
    lpp: 3.3
    mqg: 2.2
    
    mymap已空
    
    
  • 相关阅读:
    Spring Controller参数为空串的处理方式
    netstat用法
    zookeeper的配置项
    C++ Lambda表达式用法
    java命令行运行jar里的main类
    Random的nextInt用法
    【JAVA】删除某个目录及目录下的所有子目录和文件
    Centos7设置keepAlived开机自启动
    linux设置nginx开机自启动
    window.open()方法
  • 原文地址:https://www.cnblogs.com/xxmmqg/p/13412626.html
Copyright © 2020-2023  润新知