|
|
发表于 2012-3-26 20:35:50
|
显示全部楼层
给个利用C++ STL 特性的代码:
先建立文件: D:\data.txt,内容如下(表示1到5号学生的各门成绩):
1 89 34 19
3 99 98 22
2 19 17 12
5 66 78 99
4 22 55 66
程序代码:- #include <iostream>
- #include <fstream>
- #include <iterator>
- #include <algorithm>
- #include <vector>
- using namespace std;
- struct Stu{
- int no;
- float eng;
- float math;
- float phy;
- float sum;
- };
- inline istream& operator>>(istream& in, Stu& s){
- in>>s.no>>s.eng>>s.math>>s.phy;
- s.sum =s.eng+s.math+s.phy;
- return in;
- }
- inline ostream& operator<<(ostream& out, const Stu& s){
- return out<<"Number:"<<s.no<<"\t"
- <<"Eng:"<<s.eng<<"\t"
- <<"Math:"<<s.math<<"\t"
- <<"Phy:"<<s.phy<<"\t"
- <<"Sum:"<<s.sum;
- }
- inline bool sum_less(const Stu& a, const Stu& b){
- return a.sum<b.sum;
- }
- inline bool num_less(const Stu& a, const Stu& b){
- return a.no<b.no;
- }
- inline bool math_less(const Stu& a, const Stu& b){
- return a.math<b.math;
- }
- int main(){
- vector<Stu> vec;
- ifstream in("E:\\data.txt");
- typedef istream_iterator<Stu> IsIT;
- copy( IsIT(in),IsIT(), back_inserter(vec) );
- cout<<"\n------------------sort by sum-----------------\n";
- sort( vec.begin(), vec.end(), sum_less );
- copy( vec.begin(), vec.end(),ostream_iterator<Stu>(cout,"\n") );
- cout<<"\n------------------sort by no-----------------\n";
- sort( vec.begin(), vec.end(), num_less );
- copy( vec.begin(), vec.end(),ostream_iterator<Stu>(cout,"\n") );
- cout<<"\n------------------sort by math-----------------\n";
- sort( vec.begin(), vec.end(), math_less );
- copy( vec.begin(), vec.end(),ostream_iterator<Stu>(cout,"\n") );
- }
复制代码 |
|