Victory Salta
Victory Salta

Reputation: 55

How to sort a map in C++ by value but if values are equal by keys?

I want to sort my map by ints, in decreasing order, but if values are equal, I want to sort by strings. I have this code where I sort a map and then write first k values to a vector:

   map<string, int> m;
vector<string> calc(int k) {
    typedef std::function<bool(std::pair<std::string, int>, std::pair<std::string, int>)> Comparator;

    Comparator compFunctor =
    [](std::pair<std::string, int> p1 ,std::pair<std::string, int> p2)
    {
        if(p1.second != p2.second){
            return p1.second > p2.second;
        }else{
            return p1.first > p2.first;
        }

    };
    std::set<std::pair<std::string, int>, Comparator> setOfWords(m.begin(), m.end(), compFunctor);
    int c = 0;
    vector<string> str;
    for(auto it = m.begin(); it != m.end(); it++){
        if(c >= k){
            break;
        }
        str.push_back(it->first);
        c += 1;
    }
    for(int i = 0; i<str.size(); i++){
        cout << str[i] << " ";
    }

    return str;
}
};

However, it doesn't sort.

        auto cmp = [](std::pair<int,string> const & p1, std::pair<int,string> const & p2)
    {
                    if(p1.second != p2.second){
                        return p2.second > p1.second;
                  //  }
                 //   return true;
                    }else{
                        return p2.first > p1.first;
                    }
    };
    std::sort(m.begin(), m.end(), cmp);

I tried this as well but it doesn't even compile. It gives me Invalid operands to binary expression ('std::__1::__map_iterator, int>, std::__1::__tree_node, int>, void *> *, long> >' and 'std::__1::__map_iterator, int>, std::__1::__tree_node, int>, void *> *, long> >')

Upvotes: 0

Views: 427

Answers (2)

Caleth
Caleth

Reputation: 62636

A simple way of comparing by thing1 then thing2 then ... is to use std::tuple's operator <, and std::tie to make a tuple by reference

using Item = std::pair<std::string, int>;
auto cmp = [](const Item & lhs, const Item & rhs) 
{ 
    return std::tie(lhs.second, lhs.first) < std::tie(rhs.second, rhs.first);
}

Upvotes: 0

Narek Bojikian
Narek Bojikian

Reputation: 281

It's working you only should loop over "setOfWords" instead of "m" when getting the sorted results.

    for(auto it = m.begin(); it != m.end(); it++){

Upvotes: 2

Related Questions