[英]How to iterate a map of string and structure in C++?
我正在尝试迭代下面的地图,并打印出C ++中的所有内容。
struct employee
{
uint16_t id;
uint8_t lastModifiedDate[8];
std::string value;
};
std::map<std::string, employee> m1;
如您所见,上面的地图是员工的键字符串和值类型...
下面是我给出的尝试,但是无论如何,只要编译上面的代码,我的控制台都会出现一堆异常。.我不确定哪个错误将复制粘贴到这里是有意义的...所以这就是为什么我不粘贴它如果有人需要,我可以将其缩小,然后将其复制到这里。
std:map<std::string, employee>::const_iterator itMap = m1.begin();
for (;itMap !=m1.end(); ++itMap) {
std::cout << itMap->first << " : " << itMap->second << std::endl;
}
std::cout << std::endl;
知道我在这里做什么错吗?
更新: -
这是我看到的错误消息-
错误:std :: operator <<>((*&std :: operator <<,std :: allocator>((*&std :: cout),(*&itMap.std :: _Rb_tree_const_iterator <_Tp> :: operator->,employee>>()-> std :: pair,employee> :: first))),(((const char *)“:”))<< itMap.std :: _ Rb_tree_const_iterator <_Tp> :: operator->,员工>>()-> std :: pair,员工> :: second
std::cout
将不知道如何打印您employee
,直到你重写operator<<
对employee
类型。 像这样:
std::ostream& operator<<(std::ostream& os, const employee& e)
{
os << e.id << lastModifiedDate[0] << value;
rteurn os;
}
您需要指定要输出到cout
的employee
成员
std:map<std::string, employee>::const_iterator itMap = m1.begin();
for (;itMap !=m1.end(); ++itMap) {
std::cout << itMap->first << " : " << itMap->second.value << std::endl;
// ^^^^^^
}
std::cout << std::endl;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.