简体   繁体   English

打印出键为结构变量的映射键值C ++

[英]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 ) 您需要做的只是( 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. firstcno类型,您需要访问所需的元素。

If you have implemented overload operator << for this, please give the code here. 如果您为此实现了重载运算符<< ,请在此处提供代码。

This is how you overload an operator: 这是使操作员overload的方式:

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. 您需要重载运算符以打印,比较或处理用户定义的对象的元素。在这里,我们必须重载ostream对象才能打印您的用户定义的对象。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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