⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 exp20_1.cpp

📁 高等教育出版社出版的C++程序设计同步实验范例 希望对用这本教材得同学有点帮助
💻 CPP
字号:
/*vector顺序容器是以动态数组为基础的顺序表,当数组空间用完时,
vector自动分配更大的空间,取代原来的数组。首先看演示程序。
*/
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;	//	C++命名空间域

class ID{				//	ID类用于记分,用于记录每个选手的名字和积分
public:
	string Name;
	int Score;
	ID():Name(""),Score(0){}
	ID(string newName,int newScore):Name(newName),Score(newScore){}
};

bool operator==(const ID &x,const ID &y) // 当名字和积分都相同时,被认为是两个相同的ID
{
	return (x.Name==y.Name)&&(x.Score==y.Score);
}

bool operator< (const ID &x,const ID& y) {	//	按照积分排序
	return x.Score<y.Score;
}

typedef vector<ID> NAMEVECTOR;	//	定义一个ID向量的模板类

int main(){
	NAMEVECTOR theVector;		//	定义一个可动态分配的ID向量
	NAMEVECTOR::iterator theIterator;	//	定义迭代器
	theVector.push_back(ID ("Karen",2));	//	初始化ID向量
	theVector.push_back(ID ("Ada",1));
	theVector.push_back(ID ("John",3));
	theVector.push_back(ID ("Grady",2));
	cout<<"Players & Scores\n";			//	输出初始的选手名字和积分
	for(theIterator = theVector.begin();theIterator != theVector.end();theIterator ++)
		cout<<theIterator->Score<<" "<<theIterator ->Name<<endl;
	cout<<endl;
	sort(theVector.begin(),theVector.end());		//	调用sort算法排序
	cout<<"Players ranked by score:\n"<<endl;	//	输出排序后的选手积分和名字
	for(theIterator = theVector.begin();theIterator != theVector.end();theIterator ++)
		cout<<theIterator->Score<<" "<<theIterator ->Name<<endl;
	cout<<endl;
	return 0;
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -