这是打印最长重复M次的字符串的代码
#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;
}
但这是错误的
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 *)(char **,char **)' to 'int (__cdecl *)(const void *,const void *)'
1> None of the functions with this name in scope match the target type
最佳答案
更改
int pstrcmp( char **p,char **q){ return strcmp(*p,*q) ;}
至
int pstrcmp(const void *p, const void *q)
{
return strcmp(*reinterpret_cast<const char**>(p), *reinterpret_cast<const char**>(q));
}
关于c++ - 打印最长重复M次的字符串,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/3316201/