zl程序教程

您现在的位置是:首页 >  后端

当前栏目

C++ map 根据value找key、 根据key找value

C++Map Key value 根据
2023-06-13 09:12:41 时间

大家好,又见面了,我是你们的朋友全栈君。

根据 value找 key

有可能找到多个结果

根据key 找 value

、、、、、、

运行效果:

代码很简单,如下:

#include<iostream>
#include<map>
#include<string>
using namespace std;
 
 int main(int argc,char**argv)
{
	map<int,char > aMap;
	/**插入初始化的元素**/
/*	//1.用insert函數插入pair
    aMap.insert(pair<string, string>("r000", "student_zero"));
 
    //2.用"array'方式插入
*/
    aMap[0] = 'o';
    aMap[1] = 'a';
    aMap[2] = 'b';
    aMap[3] = 'c';
    aMap[4] = 'd';
    aMap[5] = 'd';//故意弄个重复的value 
    
	int key =2;
	char value='d';
	
	//通过key找value 
	if(aMap.count(key)>0)
	{
    	cout<<"通过key:  "<<key<<"     找到的value:"<<aMap[key]<<endl;
	}
	
	//通过value找 key
	for(std::map<int,char>::iterator it = aMap.begin();it!=aMap.end();it++) 
	{
		if(it->second==value)
			cout<<"通过value:  "<<value<<"    找到的key:"<<it->first<<endl;
	} 
 
}

发布者:全栈程序员栈长,转载请注明出处:https://javaforall.cn/163549.html原文链接:https://javaforall.cn