难点:
注意其中的begin() … 另外注意advance(pnum, j);中的pnum 以及(pstart + i)中的pstart 什么时候迭代器需要重新指向头部
main.cpp
#include <iostream>
#include<list>
#include<algorithm>
using namespace std;
class stu
{
public:
stu()
{
}
stu(string name)
{
this->name=name;
}
float score=0.0f;
string name;
};
list<stu>::iterator &operator +(list<stu>::iterator &midpstart, int pos)
{
while(pos--)
{
midpstart++;
}
return midpstart;
}
bool mysort(float a,float b)
{
return a>b;
}
int main()
{
list<stu>l1;
l1.push_back(stu("赵四"));
l1.push_back(stu("陈五"));
l1.push_front(stu("王一"));
l1.insert(l1.begin(), stu("李二"));
l1.insert(l1.begin(), stu("张三"));
for_each(l1.begin(), l1.end(), [=](const stu&a){
cout << a.name << endl;
});
int n = l1.size();
for(int i = 0; i < n; i++)
{
list<stu>::iterator pstart = l1.begin();
list<int>l1_num;
cout<< "给 " << (pstart + i)->name << " 学生打分"<< endl;
for(int j = 0; j < n; j++)
{
list<int>::iterator pnum = l1_num.begin();
int midnum = 0;
cin >> midnum;
advance(pnum, j);
l1_num.insert(pnum, midnum);
}
l1_num.sort(mysort);
l1_num.pop_back();
l1_num.pop_front();
cout << "验证:去除最高最低的分数是"<< endl;
for_each(l1_num.begin(), l1_num.end(), [=](const int a){
cout << a << endl;
});
list<int>::iterator pnum2 = l1_num.begin();
int score_num = 0;
for( ; pnum2 != l1_num.end(); )
{
score_num += *pnum2;
pnum2++;
}
pstart = l1.begin();
int avg = score_num / l1_num.size();
(pstart + i)->score = avg;
cout << pstart->name << "的平均分是 " << pstart->score << endl;
}
for(list<stu>::iterator it = l1.begin(); it != l1.end(); it++)
{
cout << " 姓名: "<< it->name << " 分数: " << it->score << endl;
}
return 0;
}
图示:
|