2014-10-09 103 views
42

我想遍歷map<string, int>中的每個元素,而不知道它的任何string-int值或鍵。C++循環映射

我到目前爲止有:

void output(map<string, int> table) 
{ 
     map<string, int>::iterator it; 
     for (it = table.begin(); it != table.end(); it++) 
     { 
      //How do I access each element? 
     } 
} 
+2

[如何循環訪問C++映射](http:// stackoverflow。com/questions/4844886/how-to-loop-through-ac-map) – amanuel2 2016-04-26 01:06:04

回答

117

你可以像下面實現這一點:

map<string, int>::iterator it; 

for (it = symbolTable.begin(); it != symbolTable.end(); it++) 
{ 
    std::cout << it->first // string (key) 
       << ':' 
       << it->second // string's value 
       << std::endl ; 
} 

隨着C++ 11(及以後)

for (auto const& x : symbolTable) 
{ 
    std::cout << x.first // string (key) 
       << ':' 
       << x.second // string's value 
       << std::endl ; 
} 

隨着C++ 17(及以後)

for(auto const& [key, val] : symbolTable) 
{ 
    std::cout << key   // string (key) 
       << ':' 
       << val  // string's value 
       << std::endl ; 
} 
+3

在「it」前添加「auto」類型 – iedoc 2015-04-03 13:41:29

+0

@ P0W爲什麼要爲C++ 11創建「auto const」 C++ 17? 「auto const&」和「const auto&」之間有什麼區別? – Eric 2017-06-02 02:26:50

+1

沒有區別,只是品味的問題。不過,看起來像@ P0W的味道不是很一致... – Kapichu 2017-07-06 20:16:30

8

一個mapvalue_type是包含鍵和值的,因爲它是firstsecond構件,分別pair

map<string, int>::iterator it; 
for (it = symbolTable.begin(); it != symbolTable.end(); it++) 
{ 
    std::cout << it->first << ' ' << it->second << '\n'; 
} 

或用C++ 11,使用範圍爲基礎的:

for (auto const& p : symbolTable) 
{ 
    std::cout << p.first << ' ' << p.second << '\n'; 
} 
14

嘗試使用以下

for (const auto &p : table) 
{ 
    std::cout << p.first << '\t' << p.second << std::endl; 
} 

同樣可以使用普通的for循環寫入

for (auto it = table.begin(); it != table.end(); ++it ) 
{ 
    std::cout << it->first << '\t' << it->second << std::endl; 
} 

考慮到v alue_type爲std::map是指通過以下方式

typedef pair<const Key, T> value_type 

因此,在我的例子中,p是一個const參考VALUE_TYPE,其中關鍵是std::string,T是int

此外,它會更好,如果該函數將被宣佈作爲

void output(const map<string, int> &table); 
0

由於@Vlad從莫斯科說, 要考慮到value_typestd::map定義的followi NG方式:

typedef pair<const Key, T> value_type 

這就意味着,如果你想有一個更明確的類型說明符替換關鍵字auto,那麼你會這樣;

for (const pair<const string, int> &p : table) { 
    std::cout << p.first << '\t' << p.second << std::endl; 
} 

只是爲了解auto將在這種情況下轉換爲什麼。