Print longest string duplicated M times
here is code which prints longest string duplicated M times
#include <iostream>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
using namespace std;
#define M 1
#define MAXN 5000000
char c[MAXN],*a[MAXN];
int pstrcmp( char **p,char **q){ return strcmp(*p,*q) ;}
int comlen(char *p,char *q){
int i=0;
while (*p &&(*p++==*q++)){
i++;
}
return i;
}
int main(){
int maxlen=-1;
int maxi;
int ch,n=0;
while ((ch=getchar())!=EOF){
a[n]=&c[n];
c[n++]=ch;
}
c[n]=0;
qsort(a,n,sizeof( char *),pstrcmp);
for (int i=0;i<n-M;i++)
if (comlen(a[i],a[i+M])>maxlen){
maxlen=comlen(a[i],a[i+M]);
maxi=i;
}
printf("%.*s\n",maxlen,a[maxi]);
return 0;
}
but here is mistake
1>c:\users\david\documents\visual studio 2010\projects\longest_repeted\longest_repeated.cpp(33): error C2664: 'qsort' : cannot convert parameter 4 from 'int (__cdecl 开发者_JAVA技巧*)(char **,char **)' to 'int (__cdecl *)(const void *,const void *)'
1> None of the functions with this name in scope match the target type
Change
int pstrcmp( char **p,char **q){ return strcmp(*p,*q) ;}
to
int pstrcmp(const void *p, const void *q)
{
return strcmp(*reinterpret_cast<const char**>(p), *reinterpret_cast<const char**>(q));
}
Your sort func needs to take (void*,void*)
, not (char**,char**)
. You can cast the pointers to something else inside the sort func if you need to, but they need to be pointers, not pointers-to-pointers.
Looks like the signature of pstrcmp
is wrong - should take pointers, not pointers to pointers.
精彩评论