64,700
社区成员
发帖
与我相关
我的任务
分享
#include <stdio.h>
#include <stdlib.h>
#include <queue>
#include <hash_map>
#include <string>
//#include <map>
using namespace std;
struct cmpQue{
bool operator()(pair<char*,int>p1,pair<char*,int>p2){
return stricmp(p1.first,p2.first)<0?true:false;
}
};
/*
struct cmpHash{
bool operator()(char* s1,char* s2){
return stricmp(s1,s1)==0;
}
};*/
//const char*, int, hash<const char*>, cmp
int main()
{
FILE *fin;
hash_map<char*,int> hmap;
priority_queue<pair<char*,int>,vector<pair<char*,int> >,cmpQue> hque;
fin=fopen("1.txt","r");
char word[20];
/*
strcpy(word[0],"123");
hmap[word[0]]++;
hmap[word[0]]++;
strcpy(word[1],"2");
hmap[word[1]]++;
hmap[word[1]]++;
printf("%d %d ",hmap[word[0]],hmap[word[1]]);
*/
while(fscanf(fin,"%s",word)==1)
{
++hmap[word];
}
fseek(fin,0,0);
while(fscanf(fin,"%s",word)==1)
{
if(hque.size()<10)
{
hque.push(*hmap.find(word));
}
else
{
if(hmap[word]>hque.top().second)
{
hque.pop();
hque.push(make_pair(word,hmap[word]));
}
}
}
while(!hque.empty())
{
printf("%s```````````````%d\n",hque.top().first,hque.top().second);
hque.pop();
}
return 0;
}
a
b
c
a
b
b
b
t
e
^Z
b,4
a,2
c,1
t,1
e,1
请按任意键继续. . .
#include <cstdio>
#include <cstdlib>
#include <queue>
#include <hash_map>
#include <string>
#include <vector>
using namespace std;
using namespace stdext;
struct CmpQueue;
typedef hash_map<string,int> HashMap;
typedef pair<string,int> QueuePair;
typedef priority_queue<QueuePair,vector<QueuePair>,CmpQueue> Heap;
struct CmpQueue
{
bool operator()(const QueuePair &left,const QueuePair &right)
{
return left.second<right.second;
}
};
int main()
{
FILE *fin=stdin;
HashMap hashMap;
char word[20];
while(fgets(word,20,fin)!=NULL)
{
word[strlen(word)-1]=0;
HashMap::iterator iter;
if( (iter=hashMap.find(word)) == hashMap.end() )
{
hashMap.insert(HashMap::value_type(word,1));
}
else
{
++iter->second;
}
}
Heap heap(hashMap.begin(),hashMap.end());
int cnt=0;
while(!heap.empty() && cnt!=10)
{
printf("%s,%d\n",heap.top().first.c_str(),heap.top().second);
heap.pop(),++cnt;
}
return 0;
}
肯定不对,因为你存的都是同一个char word[]数组的地址,用string对象代替char *吧。