[英]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.