如何从无序列图中打印私有类变量
How do I print private class variables from an 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;
}
unordered_map
由键值对元素组成。键和值相应地称为 first
和 second
。
鉴于您的情况,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
}
相关文章:
- 查找后更改类变量
- 如何避免在仅标头库中C++类/变量重定义
- c++ 在非类函数中使用类变量
- 基于模板的类变量
- 分段 访问私有类变量时出错
- 为什么从另一个构造函数内部调用C++构造函数不修改类变量?
- 如何访问基类向量中的子类变量?(对于实体组件系统)
- 打印类中的变量
- 模板类变量作为非模板类的成员
- 使用更改此变量的函数在同一行中打印引用变量
- C++11 - 获取编译时的所有类变量,并在没有 Boost 的情况下为它们调用方法
- 如何在构造函数中访问类变量以分配它们,而无需在C++中使用此指针
- 类变量无法从类方法访问
- 指针作为类变量 Qt
- 为什么线程对类变量所做的更改没有影响?
- memcpy() 在一个类中被调用以复制到另一个类变量中后会引发异常
- C++ 类变量未打印分配的正确值
- 如何从无序列图中打印私有类变量
- 使用Friend函数和operator+添加类变量并打印出来
- 从gdb模板类的成员函数中打印静态变量