【发布时间】:2020-10-18 07:34:38
【问题描述】:
我有 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;
}
【问题讨论】:
-
为什么是 2 个向量?无法将 2 个数据集对应在一起,因此排序一个将与另一个不同步。为什么不使用 1 个向量来保存结构/类类型的元素?这样,学生信息就作为一个数据单元保存在一起。
-
实际上输入是作为两个单独的列表提供给我的
-
不过,它不会阻止您将其存储为单个结构向量。
-
我知道我可以创建另一个向量,例如
std::vector<std::pair<int32_t, std::string>>,并根据该对的第一个元素进行排序。但这不必要地消耗了额外的空间。所以只是为了寻找更好的方法 -
@Harry 具有 1 个对向量不使用比相同数据的 2 个单独向量更多的内存。你试图做的事情不能按照你展示的方式完成。您需要将数据合并到 1 个向量中,或者使用第 3 个向量将其他 2 个向量链接在一起。
标签: c++