2011-02-14 35 views
0
typedef map <int, string> MAP_INT_STRING; 

    MAP_INT_STRING mapIntToString; 
    mapIntToString.insert (MAP_INT_STRING::value_type (3, 「Three」)); 

我只找到了通過源代碼將值插入地圖的示例。我想知道如何讓程序運行時用戶這樣做。我形象這將涉及某種形式的循環,但我不知道如何設置它。將值插入地圖

+1

給他們的源代碼的副本:) –

+0

你能澄清你的問題,或許還有一個用例或場景?用戶如何與系統進行交互? – jmort253

回答

2

現在,認真講話。首先,您需要從用戶那裏獲取值,然後將其插入到您的地圖中。是這樣的:

std::map<int, std::string> m; 
while (true) { 
    std::cout << "please give me an int\n"; 
    int i; 
    std::cin >> i; 
    std::cout << "now gimme some string\n"; 
    std::string s; 
    std::cin >> s; 
    m.insert(std::make_pair(i, s)); 
    std::cout << "continue? (y/n)"; 
    char c; 
    std::cin >> c; 
    if (c != 'y') 
     break; 
} 
+1

如果我要求int時輸入「abc」會怎樣? –

+1

@Fred:tnx,我忘了提及:它肯定不是生產就緒的解決方案。你仍然需要實現錯誤處理 –

3
int main() { 
    using namespace std; 
    map<int, string> m; 
    cout << "Enter a number and a word: "; 
    int n; 
    string s; 
    if (!(cin >> n >> s)) { 
    cout << "Input error.\n"; 
    } 
    else { 
    m[n] = s; 
    // Or: m.insert(make_pair(n, s)); 
    } 
    return 0; 
}