在无序地图上排序cmp函数

时间:2016-09-24 20:47:54

标签: c++ comparator unordered-map

我正在尝试使用值对无序地图进行排序。

这是我的代码:

#include <iostream>
#include <algorithm>
#include <string>
#include <unordered_map>

using namespace std;

bool cmp(pair<char,int> &left, pair<char,int> &right){
    cout<<"Inside comp function"<<endl;
    return left.second < right.second;
}

int main(){
    int len;
    unordered_map<char,int> charCount;
    cin >> len;
    string s,t;
    cin >> s;
    for(int i=0;i<s.length();i++){
        if(charCount.find(s[i]) != charCount.end()){
            charCount[s[i]]++;
        }else{
            charCount.insert(make_pair<char&,int>(s[i],1));
        }
    }
    sort(charCount.begin(),charCount.end(),cmp);
    for(auto& it:charCount){
        cout <<it.first<<" -> "<<it.second<<endl;
    }
    cout<<endl;
    return 0;
}

这是我得到的错误:

In file included from /usr/include/c++/4.9/algorithm:62:0,
                 from solution.cc:21:
/usr/include/c++/4.9/bits/stl_algo.h: In instantiation of 'void std::__sort(_RandomAccessIterator, _RandomAccessIterator, _Compare) [with _RandomAccessIterator = std::__detail::_Node_iterator<std::pair<const char, int>, false, false>; _Compare = __gnu_cxx::__ops::_Iter_comp_iter<bool (*)(std::pair<char, int>&, std::pair<char, int>&)>]':
/usr/include/c++/4.9/bits/stl_algo.h:4717:78:   required from 'void std::sort(_RAIter, _RAIter, _Compare) [with _RAIter = std::__detail::_Node_iterator<std::pair<const char, int>, false, false>; _Compare = bool (*)(std::pair<char, int>&, std::pair<char, int>&)]'
solution.cc:58:49:   required from here
/usr/include/c++/4.9/bits/stl_algo.h:1968:22: error: no match for 'operator-' (operand types are 'std::__detail::_Node_iterator<std::pair<const char, int>, false, false>' and 'std::__detail::_Node_iterator<std::pair<const char, int>, false, false>')
     std::__lg(__last - __first) * 2,
                      ^
/usr/include/c++/4.9/bits/stl_algo.h:1968:22: note: candidates are:
In file included from /usr/include/c++/4.9/bits/stl_algobase.h:67:0,
                 from /usr/include/c++/4.9/bits/stl_tree.h:61,
                 from /usr/include/c++/4.9/map:60,
                 from solution.cc:1:
/usr/include/c++/4.9/bits/stl_iterator.h:328:5: note: template<class _Iterator> typename std::reverse_iterator<_Iterator>::difference_type std::operator-(const std::reverse_iterator<_Iterator>&, const std::reverse_iterator<_Iterator>&)
     operator-(const reverse_iterator<_Iterator>& __x,
     ^

有人可以指导我如何纠正比较器功能吗? 如果有人觉得这不是提出这个问题的正确论坛,我会删掉我的帖子。谢谢,期待您的帮助!!!

1 个答案:

答案 0 :(得分:4)

无序地图就是它的名字所暗示的 - 它是,嗯,无序。你不能因此而订购它。

不幸的是,这条消息太过神秘,无法解释发生了什么。基本上,C ++抱怨排序所需的map迭代器的属性,而无序容器的迭代器不存在。

如果您想使用无序地图中的数据创建一个有序容器,您需要将数据复制到您可以订购的内容中,例如矢量或数组:

vector<pair<char,int>> orderedCounts(charCount.begin(),charCount.end());
sort(orderedCounts.begin(), orderedCounts.end(), cmp);