我应该将什么变量名传递给我的函数进行排序?

What variable name should I pass to my function for sorting?

编辑:我意识到我的问题之一是我试图让我的排序函数对字符串进行排序,这显然行不通。

我需要对组织成两个向量的文件中的数据进行排序。所以我正在使用一个函数,它将按照我需要的顺序对我的数据进行排序,但是,我无法弄清楚我应该在调用和函数定义的 () 中包含哪些变量。我知道我需要传递名称和分数以便函数对其进行排序,但我不知道我是否需要说 (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;
    }
}

需要先读取所有的值,循环后再排序

排序函数声明为:

void selectionSort(vector<int>& vector_values);
//                 ~~~~~~~~~~~~

这意味着它可以通过引用接受 std::vector<int>。因此,参考您的代码,您需要传递 all_scores 因为它与排序函数所需的类型相同。

因此,您的代码将如下所示:

// Read values into the vectors
while (infile >> name >> score)
{
    all_names.push_back(name);
    all_scores.push_back(score);
}

// Values are populated, now sort here
selectionSort( all_scores );

如果您需要使用 std::vector 并且还想保留名称与其相关分数之间的关系,则替代解决方案可以是 std::vector<std::pair<std::string, int>>std::vector聚合类型,即 structclass.

有两个向量的限制,你需要将两个都传递给排序函数;并且,在交换分数时交换名称以保持它们之间的关系。

为了将来的参考,您可能需要查看 std::map 等关联容器来解决此类问题。