2011-04-24 32 views
0

我能够运行程序,但没有显示任何东西。 如果我替换.find("1")我得到编译器错误,因为const char不能更改为const int。 如果我用.find('1')替换,那么我得到的输出为“字符串不在地图中”。 我需要检索键值为1的字符串。我应该如何修改我的程序以获得所需的结果。从地图检索字符串的逻辑错误-C++

#include "stdafx.h" 
#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"; 

    if(EventType.find(1)==EventType.end()) 
    {  
     cout<<"string is not in the map!"<<endl; 
    } 

    return 0; 
} 

回答

2

先转换或密钥您的收藏我不明白你的问题是诚实的。你的钥匙类型是int,所以在find()方法中,你应该给出这个确切的int作为钥匙。代码中给出的代码是可以的。

如果没有显示任何内容您已发布的确切代码,这是因为您在地图中确实有密钥(int)1。要显示分配给该键值,你可以写:

cout << EventType.find(1)->second << endl; 

编辑还是不知道你的问题是什么,如果它是一个真正的问题。下面是代码,必须努力 - 在GCC和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; 
} 
+0

我试着用你告诉我的并且得到Debug Assertion失败!错误。 – Angus 2011-04-24 10:18:24

+0

@Beata你使用什么编译器?我用GCC 4.5试了一下,一切都很好。通过'#include“stdafx.h”'我想它是Visual C++,但是什么版本? – Archie 2011-04-24 10:20:33

+0

我不知道如何查看我使用的编译器版本...获取此信息Microsoft Visual Studio 2008版本9.0.21022.8 RTM Microsoft .NET Framework版本3.5安装版:VC Express Microsoft Visual C++ 2008 91909-152- 0000052-60784 Microsoft Visual C++ 2008 – Angus 2011-04-24 10:28:58

2

您需要将字符串的字符

typedef map<int,string> EventTypeMap; 
EventTypeMap EventType; 

EventType[1]="beata"; 
EventType[2]="jane"; 
EventType[3]="declan"; 

if(EventType.find(atoi("1"))==EventType.end()) 

typedef map<char,string> EventTypeMap; 
EventTypeMap EventType; 

EventType['1']="beata"; 
EventType['2']="jane"; 
EventType['3']="declan"; 

if(EventType.find('1')==EventType.end()) 
+0

我在这两种形式尝试,但我没有得到的output.when试图与一日一我得到一个编译器错误那atoi不能转换字符从const char * .when尝试与第二个没有编译器错误和没有输出。 – Angus 2011-04-24 10:14:35

+0

修复了你的问题 – sehe 2011-04-24 10:27:38