2016-01-28 48 views
2

的地圖順序,爲什麼我的輸出是這樣的:C++我想知道對象

This : 1 
a : 4 
is : 2 
just : 3 
test : 5 

當我的代碼如下所示:

map<string, int> wordCount; 
wordCount["This"] = 1; 
wordCount["is"] = 2; 
wordCount["just"] = 3; 
wordCount["a"] = 4; 
wordCount["test"] = 5; 
for (map<string, int>::iterator it = wordCount.begin(); 
     it != wordCount.end(); it++) { 
    cout << it->first << " : " << it->second << endl; 
} 

我的問題是,在一個地圖存儲對象隨機順序?

回答

5

地圖以排序順序存儲內容。 "This"之前的原因是"a"'T'在大多數(如果不是所有字符集)之前,所以'T' < 'a',因此"This"之前"a"因爲沒有考慮字符串的長度。

如果更改Thisthis,那麼你會得到

a : 4 
is : 2 
just : 3 
test : 5 
this : 1 

Live Example

+0

謝謝您了! – TonicGin