【问题标题】:How do I print private class variables from an unordered map如何从无序映射中打印私有类变量
【发布时间】:2017-03-24 00:40:01
【问题描述】:

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

【问题讨论】:

  • 能否请您创建一个minimal reproducible example 并尽可能具体地说明您的问题?
  • 我现在就这么做。谢谢!抱歉,这是我在这个网站上的第一篇文章。
  • @key199 如果这是您的第一篇文章,您应该至少选择tour,然后继续阅读How to Ask。这些页面应该已经为您提供了这些指南。所以,这是我第一次不是借口。
  • 感谢您分享游览的链接以及如何提问。我将立即阅读它们。

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


【解决方案1】:

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
        }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-02-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-02-03
    • 2020-10-13
    • 2012-12-13
    相关资源
    最近更新 更多