2014-02-06 132 views
0

我想通過映射迭代讀出一個字符串,然後將矢量中的所有數字讀出到一個文件中。我複製並粘貼了typedef行,然後將其調整爲我的代碼,所以我不積極,這是正確的。無論如何,Visual Studio在我的循環中給我使用iterator_variable的錯誤。它說類型名稱是不允許的。我怎樣才能解決這個問題?C++:迭代通過映射

ofstream output("output.txt"); 
typedef map<string, vector<int>>::iterator iterator_variable; 
for (iterator_variable iterator = misspelled_words.begin(); iterator != misspelled_words.end(); iterator++) 
{ 
    output << iterator_variable->first; 
    for (int i = 0; i < misspelled_words.size(); i++) 
    { 
     output << " " << iterator_variable->second[i]; 
    } 
    output << endl; 
} 
+0

正如錯誤說,'iterator_variable'是一種類型的,與'for'的主體內的變量'iterator'的名稱替換它。內部的'for'也是可疑的。你確定你想循環'[0,misspelled_words.size()]'而不是'[0,iterator-> second.size())'嗎? – Praetorian

回答

2

你應該訪問迭代器像iterator->first而不是iterator_variable->first

而對於內循環,您可能需要遍歷0到iterator->second.size()而不是misspelled_words.size()

ofstream output("output.txt"); 
typedef map<string, vector<int>>::iterator iterator_variable; 
for (iterator_variable iterator = misspelled_words.begin(); iterator != misspelled_words.end(); iterator++) 
{ 
    output << iterator->first; 
    for (int i = 0; i < iterator->second.size(); i++) 
    { 
     output << " " << iterator->second[i]; 
    } 
    output << endl; 
} 
1

您可以使用基於循環和自動的新範圍來獲得更簡潔和可讀的代碼。

ofstream output("output.txt"); 
for (auto const & ref: misspelled_words) { 
    output << ref.first; 
    for (auto const & ref2 : ref.second) { 
     output << " " << ref2; 
    } 
    output << "\n"; // endl force a stream flush and slow down things. 
}