简体   繁体   English

如何在C ++中迭代字符串和结构的映射?

[英]How to iterate a map of string and structure in C++?

I am trying to iterate the below map and prints out everything in C++. 我正在尝试迭代下面的地图,并打印出C ++中的所有内容。

struct employee
{
    uint16_t id;
    uint8_t lastModifiedDate[8];
    std::string value;
};

std::map<std::string, employee> m1;

As you can see the above map is of type key string and value as employee... 如您所见,上面的地图是员工的键字符串和值类型...

Below is try I have given but somehow whenever I compile the above code, I get bunch of exceptions at my console.. I am not sure which error will make sense to copy paste it here... So that's why I am not pasting it here for now.. If somebody needs it, I can make it small and then copy it here.. 下面是我给出的尝试,但是无论如何,只要编译上面的代码,我的控制台都会出现一堆异常。.我不确定哪个错误将复制粘贴到这里是有意义的...所以这就是为什么我不粘贴它如果有人需要,我可以将其缩小,然后将其复制到这里。

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;

Any idea what wrong I am doing here? 知道我在这里做什么错吗?

Update:- 更新: -

This is the error message I am seeing - 这是我看到的错误消息-

error: no match for operator<< in 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->, employee> >()->std::pair, employee>::second 错误: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 won't know how to print your employee until you override operator<< for employee type. std::cout将不知道如何打印您employee ,直到你重写operator<<employee类型。 Like this: 像这样:

std::ostream& operator<<(std::ostream& os, const employee& e)
{
    os << e.id << lastModifiedDate[0] << value;
    rteurn os;
}

You need to specify which member of the employee that you want to output to cout 您需要指定要输出到coutemployee成员

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM