【发布时间】:2015-07-01 21:12:40
【问题描述】:
所以,我有以下代码:
#include <iostream>
#include <unordered_map>
#include <utility>
#include <map>
using namespace std;
struct cmp
{
bool operator() (const pair<int,int>&a, const pair<int,int>&b)
{
if (a.first == b.first)
return a.second<b.second;
else
return a.first > b.first;
}
};
int main (void)
{
int i=0,n,foo;
cin>>n;
map <int, pair<int,int>, cmp > mymap;
while (i != n)
{
//auto it = mymap.begin();
cin>>foo;
if (mymap.find(foo) == mymap.end())
{
mymap[foo].make_pair(1,i);
}
else
{
mymap[foo].first++;
}
i++;
}
auto it = mymap.begin();
while (it != mymap.end())
{
cout<<it->first<<"\t"<<it->second.first<<"\t"<<it->second.second;
cout<<"\n";
}
return 0;
}
这段代码所做的基本上是获取输入元素并按频率对它们进行排序(按降序排列)。如果两个元素的频率相同,则输出输入列表中最先出现的元素。
For ex: I/P: 2 5 2 8 5 6 8 8
O/P: 8 8 8 2 2 5 5 6
我在两个地方有疑问。首先,在我编写的比较器函数中,它似乎是正确的,但它在编译时给出了一个错误,即,
no matching function for call to object of type 'const cmp'
{return static_cast<const _Hash&>(*this)(__x);}
另外,我用于打印输出的循环是否正确,尤其是it->second.first?
【问题讨论】:
-
unordered_maps 未排序,您想改用map。 -
即使有自定义比较器,也无法排序?
-
另外,我将
unordered_map更改为map,但仍然显示相同的错误。 -
看在上帝的份上,使用 typedefs,你不厌烦到处输入
pair<int,int>吗?
标签: c++