C++ 使用std::sort compare函数对相应的其他向量元素进行排序

C++ 使用std::sort compare函数对相应的其他向量元素进行排序,c++,C++,我有两个向量,一个是int32_t类型,对应于学生的年龄,另一个是std::string类型,对应于学生的名字。我想根据年龄对学生进行排序(降序),并在学生姓名列表中反映排序的变化 #include <iostream> #include <string> #include <vector> #include <algorithm> void print(const std::vector<int32_t>& student

我有两个向量,一个是
int32_t
类型,对应于学生的年龄,另一个是
std::string
类型,对应于学生的名字。我想根据年龄对学生进行排序(降序),并在学生姓名列表中反映排序的变化

#include <iostream>
#include <string>
#include <vector>
#include <algorithm>


void print(const std::vector<int32_t>& student_age_list, const std::vector<std::string>& student_name_lsit) {
    int32_t size = student_age_list.size();
    for(int32_t i = 0; i < size; ++i)
        std::cout << "Name: " << student_name_lsit[i] << ", Age: " << student_age_list[i] << "\n";
    std::cout << std::endl;
}

int32_t main(int32_t argc, char *argv[]) {
    std::vector<int32_t> student_age_list { 23, 56, 34, 77, 23, 66, 54, 34 };
    std::vector<std::string> student_name_list { "abc", "sjdg", "gdagd", "twue", "sgfdah", "tywet", "mbmdas", "uyqwteu" };
    
    print(student_age_list, student_name_list);
    
    std::sort(student_age_list.begin(), student_age_list.end(), [](const int32_t& a, const int32_t& b) { return a > b; });
    
    std::cout << "\nAfter sort\n\n";
    print(student_age_list, student_name_list);
    
    return EXIT_SUCCESS;
}
#包括
#包括
#包括
#包括
无效打印(常数标准::矢量和学生年龄列表,常数标准::矢量和学生姓名列表){
int32_t size=student_age_list.size();
对于(int32_t i=0;istd::cout根据您显示的代码,根本无法将年龄数据与姓名数据关联起来,因此对一个向量进行排序将与另一个向量不同步

您应该使用1个向量。创建一个
结构
/
来保存每个学生的数据,然后对该数据使用1个向量。例如:

#包括
#包括
#包括
#包括

如果出于任何原因,这不是您的选择,那么您必须以某种方式将2个向量数据链接在一起。例如,您可以使用第3个向量将索引保存到其他2个向量中,然后对索引进行排序,例如:

#包括
#包括
#包括

#包含

为什么包含两个向量?无法将两个数据集对应在一起,因此对其中一个数据集进行排序会与另一个数据集不同步。为什么不使用一个向量,保存结构/类类型的元素?这样,学生信息就作为一个数据单元保存在一起。实际上,输入作为两个单独的列表提供给我,直到,它不会阻止你继续我将它存储为单个结构向量。我知道我可以创建另一个向量,如
std::vector
,并根据对中的第一个元素进行排序。但这不必要地消耗了额外的空间。因此,只是为了寻找更好的方法it@Harry拥有一对向量不会比相同数据的两个独立向量占用更多内存。Wh至少,您尝试执行的操作无法按您显示的方式完成。您需要将数据合并为一个向量,或使用第三个向量将其他两个向量链接在一起。要生成索引向量,请使用
std::iota(student\u index\u list.begin(),student\u index\u list.end(),0)
@phuclv您可以使用
iota
,这只是一个例子。