【发布时间】:2015-08-06 02:34:46
【问题描述】:
我编写了一个基本程序,用于收集学生姓名和答案并自动为它们评分。最后,我想用相应的名称按降序对分数进行排序。我了解如何对分数进行排序,但不能与学生姓名结合使用。这是我目前所拥有的。
#include "stdafx.h"
#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
//declare variables
char choice;
string studentName;
vector<char> answers;
vector<string> names;
int getStudents();
int getQuestions();
//calls function to get number of questions
int questions = getQuestions();
//Get answers
for (int i = 0; i < questions; ++i) {
cout << "What is the answer for question " << i + 1 << endl;
cin >> choice;
answers.push_back(choice);
}
//Get number of students
int students = getStudents();
//Get student names
for (int i = 0; i < students; i++) {
cout << "Student " << i + 1 << ", what is your name?" << endl;
cin >> studentName;
names.push_back(studentName);
}
int score = 0;
char studentAnswer;
vector<char> userAnswer;
vector<float> finalScore;
//gets student answers
for (int i = 0; i < students; i++) {
score = 0;
for (int j = 0; j < questions; j++) {
cout << names[i] << ", what is your answer for question " << j + 1 << "?" << endl;
cin >> studentAnswer;
userAnswer.push_back(studentAnswer);
if (userAnswer[i*questions+j] == answers[j])
score = score + 1;
}
finalScore.push_back(score);
}
//outputs scores
std::sort(finalScore.begin(), finalScore.end());
for (int i = 0; i < students; i++) {
cout << names[i] << " scored " << finalScore[i] << " out of " << questions <<
" or " << (finalScore[i] / questions) * 100 << "%" << endl;
}
system("pause");
return 0;
}
//function to get number of questions
int getQuestions()
{
int questions;
cout << "How many questions are there?" << endl;
cin >> questions;
return questions;
}
//function to get number of students
int getStudents()
{
int students;
cout << "How many students are there?" << endl;
cin >> students;
return students;
}
现在,它按降序对分数进行排序,但输出的分数名称不正确。
【问题讨论】:
-
在这里,您想了解结构/类以将
Student的概念聚合为可以一起存储和排序的单一数据类型,以及可能如何使用比较器谓词std::sort. -
感谢您的评论。我是编程新手,我认为我们没有涵盖结构或类。当我通过电子邮件向我的教授询问如何排序时,这是他的回复“输出数组看起来类似于
用于降序排序,而 用于升序排序。解决这个问题的最简单方法是在构建向量时连接这些值(在存在两位数分数的情况下使用 switch 或 IF 语句来容纳任何一位数分数等)”我不明白他的意思。跨度> -
如果您还没有了解结构或类,您可以做的是将一个 indices 数组排序到这些向量中。然后,您想使用带有
std::sort的自定义比较器,它按降序对分数进行排序(使用大于)。之后,在根据分数对这些索引进行排序后,您可以使用排序后的索引来查找每个学生的姓名和分数。 -
所以基本上你想在这种情况下有一个额外的
std::vector<int>,它的条目与学生的数量一样多。最初它可以只填充0,1,2,..,n-1,其中n是学生人数。然后你打电话给std::sort,但使用自定义比较器查看学生分数而不是那些指数。如果您知道如何在基本级别上使用structs,这会容易一些——在学习结构/类之前处理具有多个字段的数据排序有点奇怪,但这是可行的。
标签: c++ arrays sorting multidimensional-array