-2

I have an unordered map containing one class instance per key. Each instance contains one private variable called source and a getter function called getSource().

My goal is to traverse the map, using my getter function to print the variable from each class instance. In terms of output formatting, I would like to print one variable per line. What is the proper print statement to accomplish this?

unordered_map declarations:

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 traversal loop:

// 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;
}
key199
  • 9
  • 2

1 Answers1

0

An unordered_map constitutes of elements that are key-value pair. The key and value are correspondingly referred to as first and second.

Given your case, the int would be the key, and your NodeClass would be the value corresponding to the key.

As such, your question could be distilled to "how do I access the values of all keys stored in an unordered_map"?.

Here's an example that I hope would help:

        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
        }
Vada Poché
  • 763
  • 5
  • 16