如何从无序列图中打印私有类变量

How do I print private class variables from an unordered map

本文关键字:打印 类变量 无序      更新时间:2023-10-16

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

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
        }