<STL> 容器混合使用

1. 定义一个表示学生的结构(Student),其中包含一个名字(string)和一个分数(total)

2.用一个索引值(随便一个整数)和一个结构(Student)来构造pair<int,Student>

3.用pair<int,Student>作为set容器的插入元素。

这里要了解的是,这里插入到set容器的元素(pair<int,Student>)是我自定义的,因此需要定义针对pair<int,Student>进行比较大小的函数,方能插入set容器中,因为set容器是有序的。其他的就不需要解释了,直接看代码...

#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++没学得好吧...

posted on 2010-12-18 15:55  hicjiajia  阅读(649)  评论(1编辑  收藏  举报