做算法题时需要的一个子步骤,有两个 std::vector,对其中的一个进行从大到小排序,另外一个的位置对应改变
假设两个 std::vector
multimap(执行时间长,占内存大) std::multimap<int, int, std::greater<int>> m; // val, pos
for (int i = 0; i < v1.size(); i++) {
m.insert({v1[i], i});
}
// 遍历
for (auto &it : m) {
std::cout << v1[it.second] << ", " << v2[it.second] << std::endl;
}
vector (GPT3.5 给出算法,执行时间最短,占内存较优) std::vector<std::pair<int, int>> vv;
for (int i = 0; i < v1.size(); i++) {
vv.emplace_back(std::make_pair(v1[i], v2[i]));
}
std::sort(vv.begin(), vv.end(),
[](const std::pair<int, int> &a, const std::pair<int, int> &b) {
return a.first > b.first;
});
for (auto &it : vv) {
std::cout << it.first << ", " << it.second << std::endl;
}
vector 换成 vector (比 multimap 性能还要差) std::vector<std::vector<int>> vv;
for (int i = 0; i < v1.size(); i++) {
vv.emplace_back(std::vector{v1[i], v2[i]});
}
std::sort(vv.begin(), vv.end(),
[](const std::vector<int> &a, const std::vector<int> &b) {
return a[0]> b[0];
});
for (auto &it : vv) {
std::cout << it[0]<< ", " << it[1]<< std::endl;
}
std::vector<int> pos(v1.size());
std::iota(pos.begin(), pos.end(), 0); // 从 0 开始递增,调用 operator++ 方法
std::sort(pos.begin(), pos.end(), // 这个快排很巧妙,使用值的大小对下标进行排序
[&](int i, int j) { return v1[i] > v1[j]; }); // 注意这里会用到下标,所以 pos 数组初始化不能从 1 开始
for (auto i : pos) {
std::cout << v1[i] << ", " << v2[i] << std::endl;
}