总结
通过自己写这个项目,对于STL语法更为熟悉,在自己完成中,遇到了要对map容器中的value进行排序的问题,以及读csv文件的问题,特别在此记录下实现方式
map容器中的value排序
这里涉及到两个问题,一个是sort自定义类型排序,一个是map容器是不能直接排序的。
这里通过将map容器转换为vector嵌套容器实现,并用函数或谓词实现自定义类型排序
//用于vector自定义类型排序
class MyCompare
{
public:
bool operator()(pair<int,Person> a, pair<int, Person> b) {
return a.second.m_Score > b.second.m_Score;
}
};
void sortByScore(map<int, Person>& m, vector<pair<int, Person>>&vec)
{
//将map<int,Person>类型转换为vector<pair<int, Person>>并排序
for (map<int, Person>::iterator it = m.begin(); it != m.end(); it++) {
vec.push_back(pair<int, Person>(it->first, it->second));
}
sort(vec.begin(), vec.end(), MyCompare());
}
写CSV文件
一个是如何写csv,一个是怎么确定届数,用到getline函数来读取每一行,通过利用‘,’分隔符的方式读取每一个单元格的数据并存到vector<string>中,再对容器中的数据进行利用,要想进行计算还可以利用相关函数进行格式的转换
void readCSV()
{
ifstream ifs(FILENAME, ios::in);
string line;
if (!ifs.is_open())
{
cout << "比赛记录为空!" << endl;
exit(1);
}
vector<string>words;//声明一个字符串vector容器
string word;
istringstream sin;//将整行字符串line读入到字符串istringstream
//读取标题行
getline(ifs, line);
int times = 1;
int flag = 1;
//读取数据
while (getline(ifs, line))
{
//清空vector,只存当前行的数据
sin.clear();
words.clear();
sin.str(line);
word.clear();
if (times == 1)
cout << "第1届" << endl;
else if (times % 4 == 0)
{
cout << "第" << flag + 1 << "届" << endl;
flag++;
}
while (getline(sin, word, ','))//将字符串流sin中的字符读到field字符串中,以,分隔
{
words.push_back(word);//将每一格数据逐个push
}
int count = 0;
for (vector<string>::iterator it = words.begin(); it != words.end(); it++)
{
if (count == 0)
cout << "编号:" << *it << "\t";
else if (count == 1)
cout << "姓名:" << *it << "\t";
else if (count == 2)
cout << "成绩:" << *it << "\t";
else if (count == 3)
cout << "奖项:" << *it << endl;
count++;
}
times++;
}
}
后续
阅读了下黑马版本,觉得黑马版本更好些,黑马是通过multimap容器存储,将分数作为key值,编号作为value值,这样分数加入到容器后会自动排序,然后用count控制前三,将前三压入提前准备好的v2容器,是通过乱序编号直接给另一个编号好的map容器进行分数赋值就不用寻找它们之间的对应关系
//6个人一组,用临时容器保存
groupScore.insert(make_pair(avg, *it));
if (num % 6 == 0)
{
cout << "第" << num / 6 << "小组比赛名次" << endl;
for (multimap<double, int, greater<int>>::iterator it = groupScore.begin(); it != groupScore.end(); it++)
{
cout << "编号: " << it->second << " 姓名: " << this->m_Speaker[it->second].m_Name << " 成绩: " << this->m_Speaker[it->second].m_Score[this->m_Index - 1] << endl;
}
int count = 0;
//取前三名
for (multimap<double, int, greater<int>>::iterator it = groupScore.begin(); it != groupScore.end() && count < 3; it++, count++)
{
if (this->m_Index == 1)
{
v2.push_back((*it).second);
}
else
{
vVictory.push_back((*it).second);
}
}
groupScore.clear();
cout << endl;
}