我已经看到了很多根据std::map的值对其进行排序的解决方案。但是我想知道为什么不能像我写的代码那样直接使用std::sort对它进行排序。
#include <iostream>
#include <map>
#include <algorithm>
void print_values(const std::map<size_t, size_t>& map_data) {
for(const auto& my_pair : map_data)
std::cout << my_pair.first << " : " << my_pair.second << "\n";
std::cout << std::endl;
}
bool compare(const std::pair<size_t, size_t>& a, const std::pair<size_t, size_t>& b) {
return a.second > b.second;
}
int32_t main(int32_t argc, char* argv[]) {
std::map<size_t, size_t> coins_count;
coins_count.insert(std::make_pair(1, 2));
coins_count.insert(std::make_pair(2, 3));
coins_count.insert(std::make_pair(3, 4));
coins_count.insert(std::make_pair(4, 2));
coins_count.insert(std::make_pair(5, 3));
coins_count.insert(std::make_pair(6, 1));
coins_count.insert(std::make_pair(7, 2));
print_values(coins_count);
std::sort(coins_count.begin(), coins_count.end(), compare);
print_values(coins_count);
return EXIT_SUCCESS;
}发布于 2020-08-27 22:35:34
映射本身始终按键排序。所以你只能对一些其他的东西进行排序,这些东西可以引用map元素。
您可以对map迭代器数组进行排序:
std::vector<decltype(coins_count)::iterator> vec;
for (auto i = coins_count.begin(), end = coins_count.end(); i != end; ++i) {
vec.push_back(i);
}
std::sort(vec.begin(), vec.end(),
[](auto& a, auto& b) { return a->second < b->second; }
);
for(auto&& i : vec) {
std::cout << i->first << " : " << i->second << "\n";
}或者,您可以对映射键的数组进行排序:
std::vector<decltype(coins_count)::key_type> vec;
for(auto&& i : coins_count) {
vec.push_back(i.first);
}
std::sort(vec.begin(), vec.end(),
[&coins_count](auto& a, auto& b) {
return coins_count.at(a) < coins_count.at(b);
}
);
for(auto&& i : vec) {
std::cout << i << " : " << coins_count.at(i) << "\n";
}代码将输出:
6 : 1
1 : 2
4 : 2
7 : 2
2 : 3
5 : 3
3 : 4发布于 2020-08-27 22:19:34
std::map被实现为某种风格的按键排序的二进制搜索树。这意味着std::map必须始终按键排序,使用在构造时为映射定义的比较函数,以便元素查找正常工作。
发布于 2020-08-27 22:35:24
根据定义,map的元素始终以排序的方式进行维护。
您可以使用模板参数自己定义这种顺序,但不能使用std::sort手动更改元素的顺序(即使没有交换任何元素,此调用也将失败)。
https://stackoverflow.com/questions/63617780
复制相似问题