我有2个向量,其中一个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;
}
答案 0 :(得分:0)
鉴于您所显示的代码,根本无法将年龄数据与名称数据相关联,因此对一个向量进行排序将与另一向量不同步。
您应该改用1个向量。创建一个struct
/ class
来保存每个学生的数据,然后对该数据使用1个向量。例如:
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
struct StudentInfo
{
std::string name;
int32_t age;
};
void print(const std::vector<StudentInfo>& student_list) {
for(const auto &student : student_list)
std::cout << "Name: " << student.name << ", Age: " << student.age << "\n";
std::cout << std::endl;
}
int main(int argc, char *argv[]) {
std::vector<StudentInfo> student_list { {“abc”,23}, {“sjdg”,56}, {“gdagd”,34}, {“twue”,77}, {“sgfdah”,23}, {“tywet”,66}, {“mbmdas”,54}, {“uyqwteu”,34} };
print(student_list);
std::sort(student_list.begin(), student_list.end(), [](const StudentInfo& a, const StudentInfo& b) { return a.age > b.age; });
std::cout << "\nAfter sort\n\n";
print(student_list);
return EXIT_SUCCESS;
}
如果由于某种原因这不是您的选择,那么您将必须以某种方式将2个矢量数据链接在一起。例如,您可以使用第三个向量将索引保存到其他两个向量中,然后对索引进行排序,例如:
#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_list, const std::vector<size_t>& student_index_list) {
for(size_t index : student_index_list)
std::cout << "Name: " << student_name_list[index] << ", Age: " << student_age_list[index] << "\n";
std::cout << std::endl;
}
int main(int 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" };
std::vector<size_t> student_index_list { 0, 1, 2, 3, 4, 5, 6, 7 };
print(student_age_list, student_name_list, student_index_list);
std::sort(student_index_list.begin(), student_index_list.end(), [&](const size_t& a, const size_t& b) { return student_age_list[a] > student_age_list[b]; });
std::cout << "\nAfter sort\n\n";
print(student_age_list, student_name_list, student_index_list);
return EXIT_SUCCESS;
}