社区首页 >问答首页 >为什么不能根据值字段直接使用std::sort对std::map进行排序问为什么不能根据值字段直接使用std::sort对std::map进行排序ENStack Overflow用户提问于 2020-08-27 22:05:43回答 3查看 103关注 0票数 0我已经看到了很多根据std::map的值对其进行排序的解决方案。但是我想知道为什么不能像我写的代码那样直接使用std::sort对它进行排序。
代码语言:javascript复制#include
#include
#include
void print_values(const std::map
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
return a.second > b.second;
}
int32_t main(int32_t argc, char* argv[]) {
std::map
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;
}c++关注问题分享EN回答 3推荐最新Stack Overflow用户回答已采纳发布于 2020-08-27 22:35:34
映射本身始终按键排序。所以你只能对一些其他的东西进行排序,这些东西可以引用map元素。
您可以对map迭代器数组进行排序:
代码语言:javascript复制std::vector
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";
}或者,您可以对映射键的数组进行排序:
代码语言:javascript复制std::vector
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";
}代码将输出:
代码语言:javascript复制6 : 1
1 : 2
4 : 2
7 : 2
2 : 3
5 : 3
3 : 4收藏分享票数 1ENStack Overflow用户发布于 2020-08-27 22:19:34
std::map被实现为某种风格的按键排序的二进制搜索树。这意味着std::map必须始终按键排序,使用在构造时为映射定义的比较函数,以便元素查找正常工作。
收藏分享票数 2ENStack Overflow用户发布于 2020-08-27 22:35:24
根据定义,map的元素始终以排序的方式进行维护。
您可以使用模板参数自己定义这种顺序,但不能使用std::sort手动更改元素的顺序(即使没有交换任何元素,此调用也将失败)。
收藏分享票数 0EN页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持原文链接:https://stackoverflow.com/questions/63617780
复制相关文章