I could able to run the program but nothing gets displayed..
If I replace .find("1")
I'm getting compiler error as const char cannot be changed to const int.
If I replace with .find('1')
then I'm getting the output as "string is not in the map".
I need to retrieve the string with the key value 1. How should I modify my program to get the desired result.
#include "stdafx.h"
#include <iostream>
#include <map>
#include <string>
using namesp开发者_JS百科ace std;
int main()
{
typedef map<int,string> EventTypeMap;
EventTypeMap EventType;
EventType[1]="beata";
EventType[2]="jane";
EventType[3]="declan";
if(EventType.find(1)==EventType.end())
{
cout<<"string is not in the map!"<<endl;
}
return 0;
}
I don't see your problem to be honest. Your key-type is int
, so in find()
method you should give this exact int
as the key. Code given in your question is OK.
If nothing gets displayed in this exact code you have posted, it is because you do have key (int)1
in your map. To display value assigned to this key, you could write:
cout << EventType.find(1)->second << endl;
Edit Still don't know what your problem is and if it is really a problem. Here is code that must work -- tested on GCC and Visual C++ 2008:
#include <iostream>
#include <map>
#include <string>
using namespace std;
int main()
{
typedef map<int, string> EventTypeMap;
EventTypeMap EventType;
EventType[1] = "beata";
EventType[2] = "jane";
EventType[3] = "declan";
int idx = 1;
if (EventType.find(idx) == EventType.end())
cout << "string is not in the map!" << endl;
else
cout << EventType.find(idx)->second << endl;
cin.get();
return 0;
}
You need to convert the string first, or key your collection by characters
typedef map<int,string> EventTypeMap;
EventTypeMap EventType;
EventType[1]="beata";
EventType[2]="jane";
EventType[3]="declan";
if(EventType.find(atoi("1"))==EventType.end())
or
typedef map<char,string> EventTypeMap;
EventTypeMap EventType;
EventType['1']="beata";
EventType['2']="jane";
EventType['3']="declan";
if(EventType.find('1')==EventType.end())
精彩评论