2011-04-24 30 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