我寫了一個基本程序,收集學生的姓名和答案,並自動爲他們評分。最後,我想用相應的名字按降序排列分數。我瞭解如何對得分進行排序,但不能與學生姓名結合使用。這是我迄今爲止所擁有的。C++多維排序
#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'的比較謂詞。 –
感謝您的評論。我是編程新手,我不認爲我們已經覆蓋了結構或類。當我通過電子郵件發送我的教授,詢問如何進行排序,這是他爲升序名稱排序答覆 「的輸出數組將類似於爲降序評分排序,並。 容納的最簡單方法這是爲了在構建矢量時連接這些值(在開關或IF語句中,如果存在兩位數分數的情況下,容納任何單個數字分數等)。「 我不明白他的意思。 –
如果您還沒有了解結構或類,您可以改爲將_indices_排列到這些向量中。然後你想用一個自定義的比較器和'std :: sort',它們按照降序對比分(使用大於)。之後,您可以使用排序後的索引來查找每個學生的姓名和分數,然後根據分數對這些索引進行排序。 –