简体   繁体   中英

Print out map key values where key is a struct variable c++

struct cno{
    int sub;
};

A struct is taken as a key variable in map.

map<cno,int> s;
struct cno k;

I am trying to print the key value like this.

for(map<cno,int>::iterator it = s.begin();it!=s.end();it++){
    cout<<it->first<<endl;
}//Error

I have already overloaded < operator to compare the key values.

All you need to do is ( it->first.sub )

for(map<cno,int>::iterator it = s.begin();it!=s.end();it++){
    cout<<it->first.sub<<endl;
}

Why? first is of type cno , and you need to access desired element.

If you have implemented overload operator << for this, please give the code here.

This is how you overload an operator:

ostream& operator<<(ostream& out,cno &c){
    out<<c.sub<<endl;
    return out;
}

You need to overload operators in order to print,compare or process an element of an user defined object.Here we have to overload ostream object in order to print your user defined object.

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