user2467545
user2467545

Reputation:

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

Upvotes: 2

Views: 4289

Answers (2)

axon
axon

Reputation: 1200

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;

Upvotes: 0

billz
billz

Reputation: 45410

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;
}

Upvotes: 2

Related Questions