简体   繁体   中英

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++.

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::cout won't know how to print your employee until you override operator<< for employee type. 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

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;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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