排序函数:第一种做法:用STL:

目录 编程

这是老师给的程序:************stdafx.h**************
// stdafx.h : include file for standard system include files,
// or project specific include files that are used frequently, but
// are changed infrequently
//

#if !defined(AFX_STDAFX_H__12C9FDA9_9863_4D79_8C94_1739D2996569__INCLUDED_)
#define AFX_STDAFX_H__12C9FDA9_9863_4D79_8C94_1739D2996569__INCLUDED_

#if _MSC_VER > 1000
#pragma once
#endif // _MSC_VER > 1000

#define WIN32_LEAN_AND_MEAN // Exclude rarely-used stuff from Windows headers

#include<iostream>
#include<fstream>
#include<algorithm>
#include<string>
#include<vector>
#include<iomanip>

//#include <afxtempl.h>
//#include <afx.h>
#include <time.h>

// TODO: reference additional headers your program requires here

//{{AFX_INSERT_LOCATION}}
// Microsoft Visual C++ will insert additional declarations immediately before

the previous line.

#endif // !defined(AFX_STDAFX_H__12C9FDA9_9863_4D79_8C94_1739D2996569__INCLUDE

D_)

************stdafx.cpp**************
// stdafx.cpp : source file that includes just the standard includes
// GradeResort.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information

#include "stdafx.h"

// TODO: reference any additional headers you need in STDAFX.H
// and not in this file

*********************gradesort.h*****************
#ifndef SORT_METHODS_H
#define SORT_METHODS_H

#include "stdAfx.h"

using namespace std;

class Grade{
public:
string id;
string name;
int grade;
public:

void SetId(string i) { id = i; }
void SetName(string n) { name = n; }
void SetGrade(int g) { grade = g; }
string GetId() { return id; }
string GetName() { return name; }
int GetGrade() { return grade; } const

Grade(string i,string n,int g):id(i),name(n),grade(g){}
Grade() { id="";name="";grade=0;}
bool operator<(const Grade& y) const
{
if(this->grade < y.grade)
return true;
else if(this->grade == y.grade && this->id < y.id)
return true;
else
return false;
}
bool operator==(const Grade& y) const
{
return (this->grade == y.grade && this->id == y.id) ? true : false;
}
};

#endif SORT_METHODS_H

**********************graderesort.cpp*********************************
// GradeResort.cpp : Defines the entry point for the console application.
//

#include "stdAfx.h"
#include "GradeSort.h"

int main(int argc, char* argv[])
{
ifstream fin("oldgrade.txt");
vector<Grade> gVector;

Grade tempGrade;
do {
fin >> tempGrade.id >> tempGrade.name >> tempGrade.grade;
gVector.push_back(tempGrade);
} while(!fin.eof());

ofstream fout("sortedGrade.txt");
sort(gVector.begin(), gVector.end());
int cnt =gVector.size();

fout.setf(ios::left);
for(int i=0; i<cnt; i++) {
tempGrade = gVector[i];
fout << setw(15) << tempGrade.id << " "
<< setw(15) << tempGrade.name << " "
<< setw(5) << tempGrade.grade << endl;
}
return 0;
}

长按识别二维码关注《边际效应》
长按识别二维码关注《边际效应》

暂无评论

发表评论

电子邮件地址不会被公开。 必填项已用*标注