如何从无序映射中打印私有类变量

时间:2017-03-24 00:40:01

标签: c++ c++11 unordered-map

我有一个无序映射,每个键包含一个类实例。每个实例包含一个名为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;
}

1 个答案:

答案 0 :(得分: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
        }