2017-03-24 55 views
-2

我有一個無序映射,每個鍵包含一個類實例。每個實例都包含一個名爲source的私有變量和一個名爲getSource()的getter函數。如何從無序映射打印私有類變量

我的目標是遍歷地圖,使用我的getter函數從每個類實例中打印變量。在輸出格式方面,我想每行打印一個變量。什麼是適當的打印聲明來完成這個?

unordered_map聲明:

unordered_map<int, NodeClass> myMap; // Map that holds the topology from the input file 
unordered_map<int, NodeClass>::iterator mapIterator; // Iterator for traversing topology map 

unordered_map遍歷循環:

// Traverse map 
for (mapIterator = myMap.begin(); mapIterator != myMap.end(); mapIterator++) { 
     // Print "source" class variable at current key value 
} 

的getSource():

// getSource(): Source getter 
double NodeClass::getSource() { 
    return this->source; 
} 
+0

見http://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list –

+0

能否請您創建一個[mcve]並儘可能詳細地描述你的問題? –

+0

我現在應該這樣做。謝謝! 我的歉意,這是我在這個網站上的第一篇文章。 – key199

回答

0

unordered_map構成鍵值對的元素。密鑰和值相應地被稱爲firstsecond

鑑於你的情況,int將是關鍵,而你的NodeClass將是對應於該關鍵字的值。

因此,您的問題可以被提煉爲「我如何訪問存儲在unordered_map中的所有密鑰的值」?

這裏,我希望能幫助一個例子:

 using namespace std; 
     unordered_map<int, string> myMap; 

     unsigned int i = 1; 
     myMap[i++] = "One"; 
     myMap[i++] = "Two"; 
     myMap[i++] = "Three"; 
     myMap[i++] = "Four"; 
     myMap[i++] = "Five"; 

     //you could use auto - makes life much easier 
     //and use cbegin, cend as you're not modifying the stored elements but are merely printing it. 
     for (auto cit = myMap.cbegin(); cit != myMap.cend(); ++cit) 
     { 
      //you would instead use second->getSource() here. 
      cout<< cit->second.c_str() <<endl; 
      //printing could be done with cout, and newline could be printed with an endl 
     }