声明:我知道用两个向量不实用,但这是我们的任务。
这是我的提示。
在这个程序中,我们要从一个名为student. txt的文件中输入100个学生的名字和分数。这个文件已经提供给你了。你必须使用两个向量变量,一个用来存储学生的名字,另一个用来存储学生的分数。此外,修改selectSort函数,根据分数按升序对学生信息进行排序。最后,使用cout将排序后的学生信息显示在屏幕上。例如,让我们假设,下面是student.txt文件的内容(在这种情况下,我们只有4个值对)。
Jeff 77
查尔斯99
Richard 67
新浪79
那么,程序的输出将是
查尔斯99
新浪79
Jeff 77
Richard 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;
}
}
这是我的问题
代码编译得很好,显示了名字和相应的分数 但是,我的排序函数似乎什么都没做。名字的显示顺序和文件中的顺序是一样的。 我把调用放在了我认为它会去的每个位置,但没有任何变化。 我现在担心调用的位置不是问题,而是整个函数。
这条语句
cout << name << " " << score << endl;
只是打印刚才读取的两个值。你是否对中间的东西进行了排序并不重要。
但是你也没有对all_names数组进行排序。而且在添加每个项目后进行排序的效率非常低。