【发布时间】:2020-08-14 10:53:59
【问题描述】:
编辑:我意识到我的一个问题是我试图让我的排序函数对字符串进行排序,这显然是行不通的。
我需要对组织成两个向量的文件中的数据进行排序。所以我正在使用一个函数,它会按照我需要的顺序对我的数据进行排序,但是,我无法弄清楚我应该在调用的 () 和函数定义中包含哪些变量。我知道我需要传递名称和分数才能让函数对其进行排序,但我不知道我是否需要说 (string name, int score) 或 (vector, vector
//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
selectionSort();
cout << name << " "<< score<<", ";
}
}
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;
}
}
【问题讨论】:
-
selectionSort()显然是错误的,你需要传递你要排序的向量,例如selectionSort(all_names)。而且你在错误的地方调用selectionSort(),你应该只在文件被读取后调用它。但无论如何,总体方法是错误的。你不应该有 2 个向量,而是一个包含名称和分数的结构或类的单个向量。 -
... 你应该使用
的排序函数,而不是自己创建排序函数,除非这是练习的要求。 -
@Jabberwocky 我不想使用两个向量,但这是本实验室的要求
-
如果需要有两个向量并使它们保持同步,则需要将 both 向量传递给排序函数,并在交换一个向量的元素时 (您实际排序的那个)您还需要从另一个向量中交换相应的元素。
-
@yellogs 进行练习,你应该把所有要求都放在问题中,否则你会得到像上面那样的 cmets。
标签: c++ function vector selection-sort