2017-03-24 1 views
-2

キーごとに1つのクラスインスタンスを含む順序付けられていないマップがあります。各インスタンスには、sourceというプライベート変数とgetSource()というゲッター関数が含まれています。順序付けされていないマップからプライベートクラス変数を印刷する方法

私の目標は、getter関数を使って各クラスインスタンスから変数を出力してマップをトラバースすることです。出力書式に関しては、1行に1つの変数を出力したいと考えています。これを達成するための適切なプリントステートメントは何ですか?

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 
     } 
関連する問題