C++实现演讲比赛小项目

对于这个小项目,有两个只是盲区
1、定义了一个自定义数据类型的类之后,在后面创建的时候,自定义数据类型必须要有默认构造函数,如果在自定义的类里面定义了有参构造,就要自己定义一个默认构造函数。
2、自定义map容器等容器的排序的时候,传进来的参数被系统默认以const类型的形式传进来的,所以在重载operator()的时候,也需要定义为const的类型。要不然会出错。因为operator()类型会修改形参的内容,而形参的内容是const类型的,所以必须定义operator()也要是const类型的。

hpp文件

#pragma once
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 

using namespace std;

class Compare
{
public:
	bool operator()(int v1, int v2) const 
	{
		return v1 > v2;
	}
};
class Person
{
public:
	Person() {}
	Person(string Name,int Code)
	{
		this->m_Name = Name;
		this->m_Code = Code;
	}
	string m_Name;
	int m_Code;
};
vector<Person> RandomVector(vector<Person>& v)
{
	random_shuffle(v.begin(), v.end());
	return v;
}
vector<Person> SetPerson()
{
	vector<Person> v;
	string Order = "ABCDEFGHIJKLMNOP";
	int Code = 0;
	for (int i = 0; i < 12; i++)
	{
		string Name = "选手";
		Name += Order[i];
		Person p = { Name, Code };
		v.push_back(p);
		Code++;
	}
	return v;
}
vector<Person> GetGroup1(vector<Person>& v)
{
	vector<Person>::iterator i = v.begin(); 
	for (int j = 0; j < 6; j++)
	{
		i++;
	}
	vector<Person> v1;
	v1.resize(6);
	copy(v.begin(), i, v1.begin());
	return v1;
}

vector<Person> GetGroup2(vector<Person>& v)
{
	vector<Person>::iterator i = v.begin();
	for (int j = 0; j < 6; j++)
	{
		i++;
	}
	vector<Person> v2;
	v2.resize(6);
	copy(i, v.end(), v2.begin());
	return v2;
}

void SetMap(vector<Person>& v)
{
	multimap<int, Person,Compare> m;
	list<int> L;
	for (int i = 0; i < 6; i++)
	{
		for (int j = 0; j < 10; j++)
		{
			int Code = rand() % 11;
			L.push_back(Code);
		}
		int Sum = accumulate(++L.begin(), --L.end(),0);
		m.insert(make_pair(Sum, v[i]));
	}
	for (multimap<int, Person,Compare>::iterator i = m.begin(); i != m.end(); i++)
	{
		cout << i->second.m_Name << " " << i->second.m_Code << " " << i->first << endl;
	}
}

void ShowPerson( vector<Person> &v)
{
	for (vector<Person>::iterator i = v.begin(); i != v.end(); i++)
	{
		cout << "姓名:" << i->m_Name << "编号:" << i->m_Code << endl;
	}
}

cpp文件

#include "演讲比赛.hpp"

int main()
{
	srand((unsigned int)time(NULL));
	vector<Person> v = SetPerson();
	vector<Person> v1 = RandomVector(v);
	vector<Person> v2 = GetGroup1(v1);
	vector<Person> v3 = GetGroup2(v);
	SetMap(v2);
	SetMap(v3);
	//ShowPerson(v2);
	//ShowPerson(v3);
	return 0;
}

你可能感兴趣的:(C++代码)