天天看點

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

大家好,又見面了,我是你們的朋友全棧君。

根據 value找 key

有可能找到多個結果

根據key 找 value

、、、、、、

運作效果:

C++ map 根據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