![](/img/trans.png)
[英]unordered_map iterator points to end(), how can I retrieve a key from unordered_map?
[英]How do I print private class variables from an unordered map
我有一個無序映射,每個鍵包含一個類實例。 每個實例都包含一個名為 source 的私有變量和一個名為 getSource() 的 getter 函數。
我的目標是遍歷地圖,使用我的 getter 函數打印每個類實例中的變量。 在輸出格式方面,我想每行打印一個變量。 完成此操作的正確打印語句是什么?
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
// Traverse map
for (mapIterator = myMap.begin(); mapIterator != myMap.end(); mapIterator++) {
// Print "source" class variable at current key value
}
// getSource(): Source getter
double NodeClass::getSource() {
return this->source;
}
unordered_map
由鍵值對的元素組成。 鍵和值對應地稱為first
和second
。
鑒於您的情況, 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
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.