【发布时间】:2020-08-15 10:53:12
【问题描述】:
免责声明:我知道使用两个向量是不切实际的,但这是我们的任务。
这是我的提示:
在这个程序中,我们将从一个名为的文件中输入 100 名学生的姓名和分数 学生.txt。该文件已提供给您。您必须使用两个向量变量,一个用于存储 学生姓名,另一个用于存储学生成绩。此外,将 selectionSort 函数修改为 根据分数升序对学生信息进行排序。最后,显示排序的学生 使用 cout 在屏幕上显示信息。 例如,让我们假设,以下是 student.txt 文件的内容(在这种情况下,我们有 只有 4 个值对)。
杰夫 77
查尔斯 99
理查德 67
新浪79
那么,程序的输出将是
查尔斯 99
新浪79
杰夫 77
理查德 67
这是我的代码:
//Name
//This program will read and sort names and grades from a file using functions and vectors
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
#include <vector>
using namespace std;
//Function prototype
void selectionSort(vector<int>& vector_values);
int main()
{
ifstream infile;
infile.open("student.txt");
if (infile.fail() == false)
{
vector<string> all_names;
vector<int> all_scores;
string name;
int score;
while (infile >> name >> score) // read one name and one score
{
all_names.push_back(name); // add that name to vector
all_scores.push_back(score); // add that score to vector
int count = 0;
const int max = 1;
selectionSort(all_scores);
while (count < max)
{
count++;
cout << name << " " << score << endl;
}
}
}
else
{
cout << "Could not open the file." << endl;
}
return 0;
}
void selectionSort(vector<int>& vector_values)
{
for (unsigned pass = 0; pass < vector_values.size(); pass++)
{
int minimum = vector_values[pass];
int minimum_index = pass;
for (unsigned index = pass + 1; index < vector_values.size(); index++)
{
if (minimum > vector_values[index])
{
minimum = vector_values[index];
minimum_index = index;
}
}
int temp = vector_values[minimum_index];
vector_values[minimum_index] = vector_values[pass];
vector_values[pass] = temp;
}
}
这是我的问题:
代码编译得很好,并显示了名称及其相应的分数,但是,我的排序函数似乎完全没有做任何事情。名称的显示顺序与它们最初在文件中的显示顺序相同。我已经在我认为会去的每个位置拨打了电话,但没有任何改变。我现在担心调用的位置不是问题,而是整个函数。
【问题讨论】:
-
你的排序函数只接受一个向量你觉得不奇怪吗?另外,为什么要在每个学生运行一次的循环中调用 sort 函数?见ericlippert.com/2014/03/05/how-to-debug-small-programs。
-
实际上你可以有很多向量并且仍然可以只使用一个向量进行排序,并且所有其他向量都会排序出来。诀窍是不对向量中的数据进行排序,而是对用作索引的单个整数向量进行排序。 See this。阅读答案和答案中的脚注。听起来有点熟?您的分配属于“并行数组排序”类别,可以使用单个辅助索引数组来完成。
标签: c++ function sorting vector ifstream