I have a map of map map<int, map<char,int> > m;
and i want to sort it by the 2nd element of inner map ie, by the int value of map<char, int>
in descending order
i used this to sort 2nd element of a map but here i want to sort 2nd element of inner map in descending order
template <typename T1, typename T2>
struct less_second {
typedef pair<T1, T2> type;
bool operator ()(type const& a, type const& b) const {
return a.second < b.second;
}
};
map<string, int> mymap;
// …
vector<pair<string, int> > mapcopy(mymap.begin(), mymap.end());
sort(mapcopy.begin(), mapcopy.end(), less_second<string, int>());
edit: for example my map has the following values:
{3 {A 1}
{D 2}},
{6 {C 2}},
{9 {A 1}
{B 2}},
{12 {B 3}
{C 1}}
then it should be sorted as per 2nd element of inner map in descending order
{12 {B 3}
{C 1}},
{6 {C 2}},
{3 {A 1}
{D 2}},
{9 {A 1}
{B 2}}
This copies the elements of a map<int, map<char, int>>
into into a vector<pair<int, map<char, int>>>
and sorts the vector by the value of the first element in the map
#include <numeric>
#include <iostream>
#include <map>
#include <string>
#include <vector>
using std::cout;
using std::pair;
using std::string;
using std::vector;
using namespace std::literals::string_literals;
auto f1(const std::map<char, int> &m) {
return std::accumulate(
std::next(std::begin(m)),
std::end(m),
std::begin(m)->first + ": "s + std::to_string(std::begin(m)->second),
[](const auto &lhs, const auto &rhs) {
return lhs + ", "s + rhs.first + ": "s + std::to_string(rhs.second);
});
}
auto &operator<<(std::ostream &os, const std::vector<std::pair<int, std::map<char, int>>> &m) {
return os << "{\n"
<< std::accumulate(
std::next(std::begin(m)),
std::end(m),
std::to_string(std::begin(m)->first) + ": { "s + f1(std::begin(m)->second) + " }"s,
[](const auto &lhs, const auto &rhs) {
return lhs + ",\n"s + std::to_string(rhs.first) + ": { "s + f1(rhs.second) + " }"s;
})
<< "\n}\n";
}
int main() {
std::map<int, std::map<char, int>> mymap{ {3, {{'A', 1}, {'D', 2}}}, {6, {{'C', 2}}}, {9, {{'A', 1}, {'B', 2}}}, {12, {{'B', 3}, {'C', 1}}} };
std::vector<std::pair<int, std::map<char, int>>> mapcopy(mymap.begin(), mymap.end());
sort(mapcopy.begin(), mapcopy.end(), [](const auto &lhs, const auto &rhs){
return lhs.second.cbegin()->second > rhs.second.cbegin()->second;
});
std::cout << mapcopy;
}
Output:
{
12: { B: 3, C: 1 },
6: { C: 2 },
3: { A: 1, D: 2 },
9: { A: 1, B: 2 }
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.