原文链接:Sort a map by values in C++
在这篇博客中,我们将讲解如何针对C++的Map的value进行排序。
我们知道 std::map 这个容器默认是根据 键 来排序的,而不是 值。这篇博客讲通过一些方法来对 值 排序。
1:使用 std::vector
#include <iostream> #include <map> #include <vector> #include <algorithm> typedef std::pair<std::string,int> pair; int main() { // input map std::map<std::string,int> map = { {"two", 2}, {"one", 1}, {"four", 4}, {"three", 3} }; // create a empty vector of pairs std::vector<pair> vec; // copy key-value pairs from the map to the vector std::copy(map.begin(), map.end(), std::back_inserter<std::vector<pair>>(vec)); // sort the vector by increasing order of its pair's second value // if second value are equal, order by the pair's first value std::sort(vec.begin(), vec.end(), [](const pair& l, const pair& r) { if (l.second != r.second) return l.second < r.second; return l.first < r.first; }); // print the vector for (auto const &pair: vec) { std::cout << '{' << pair.first << "," << pair.second << '}' << '\n'; } return 0; }
输出结果:
{one,1} {two,2} {three,3} {four,4}
2:使用std::set
#include <iostream> #include <map> #include <set> // Comparison function for sorting the set by increasing order of its pair's // second value. If second value are equal, order by the pair's first value struct comp { template<typename T> bool operator()(const T& l, const T& r) const { if (l.second != r.second) return l.second < r.second; return l.first < r.first; } }; int main() { // input map std::map<std::string,int> map = { {"two", 2}, {"one", 1}, {"four", 4}, {"three", 3} }; // create a empty vector of pairs std::set<std::pair<std::string,int>, comp> set(map.begin(), map.end()); // print the vector for (auto const &pair: set) { std::cout << '{' << pair.first << "," << pair.second << '}' << '\n'; } return 0; }
输出结果:
{one,1} {two,2} {three,3} {four,4}
3:使用std::multimap
#include <iostream> #include <map> #include <set> #include <algorithm> // Function to convert a std::map<K,V> to std::multimap<V,K> template<typename K, typename V> std::multimap<V,K> invertMap(std::map<K,V> const &map) { std::multimap<V,K> multimap; for (auto const &pair: map) { multimap.insert(std::make_pair(pair.second, pair.first)); } return multimap; } int main() { // input map std::map<std::string,int> map = { {"two", 2}, {"one", 1}, {"four", 4}, {"three", 3} }; // invert the map std::multimap<int,std::string> multimap = invertMap(map); // print the multimap for (auto const &pair: multimap) { std::cout << '{' << pair.second << "," << pair.first << '}' << '\n'; } return 0; }
输出结果:
{one,1} {two,2} {three,3} {four,4}
感谢阅读~Happy Coding~
文章的脚注信息由WordPress的wp-posturl插件自动生成