- 定义一个表示学生的结构(Student),其中包含一个名字(string)和一个分数(total)
2.用一个索引值(随便一个整数)和一个结构(Student)来构造pair
3.用pair
这里要了解的是,这里插入到set容器的元素(pair
#include <iostream>#include <utility> // 使用pair<> #include <string>#include <set>using namespace std;struct Student{ string name; int total; friend ostream& operator<<(ostream& os,const Student& st) { os<<st.name<<" "<<st.total<<endl; return os; }};bool operator<(const pair<int,Student>& p1,const pair<int,Student>& p2) // 给出pair<int,Student>类型的比较函数 { return p1.first<p2.first;}int main(){ Student student[2]={ {"hicjiajia",427}, {"abcdefghi",429} }; pair<int,Student> p1(31,student[0]); // 定义两个pair<int,Student>对象 pair<int,Student> p2(21,student[1]); // 定义两个pair<int,Student>对象 set<pair<int,Student> > ss; //pair<int,Student>类型作为set容器的插入类型 ss.insert(p1); ss.insert(p2); set<pair<int,Student> >::iterator it=ss.begin(); for (; it!=ss.end(); it++) //cout<<(*it).first<<" "<<(*it).second.name<<" "<<(*it).second.total<<endl; cout<<(*it).first<<" "<<(*it).second<<endl; //输出结果,输出(*it).second元素时会调用Student的operator<<()函数进行输出 system("pause"); return 0;}
注意:在Student结构中,我重写了operator<<(),以方便输出,请注意第二个参数的类型要为 const &,我一开始写的是Student& 总是报错,后来试着改成const Student& 就OK了,不知道为什么,可能是我C++没学得好吧...
原文链接: https://www.cnblogs.com/hicjiajia/archive/2010/12/18/1910042.html
欢迎关注
微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍
原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/18942
非原创文章文中已经注明原地址,如有侵权,联系删除
关注公众号【高性能架构探索】,第一时间获取最新文章
转载文章受原作者版权保护。转载请注明原作者出处!