我写了下面的代码来计算名字的频率,然后按字典顺序打印出名字及其频率。这里的输入应该是 n 个名字。所以为了排序我写了 qsort 函数,但我猜那里其中有一些错误,我无法使用除 qsort 之外的其他排序方法找到 bcoz 对于此代码工作正常。请提出错误是什么,因为我已经尝试但没有找到帮助。下面是代码片段
#include <cstdlib>
#include<stdio.h>
#include<string.h>
struct stu
{
char name[100];
int no;
};
int cmpfunc(const void* p,const void *q){
struct stu *a = *((struct stu**)p);
struct stu *b = *((struct stu**)q);
int str=strcmp(a->name,b->name);
if(str>0) return 1;
if(str<0) return -1;
else return 0;
}
int main(int argc, char** argv) {
int n,k=0;
scanf("%d",&n);
struct stu* data[1000];
for(int i=0 ; i<n ; i++)
{
char nam[100];
scanf("%s",nam);
if(i==0)
{
struct stu* temp=(struct stu*)(malloc(sizeof(struct stu)));
strcpy(temp->name,nam);
temp->no=1;
data[k++]=temp;
}
else
{
int j;
for(j=0 ; j<k ; j++)
{
if(strcmp(data[j]->name,nam)==0)
{
data[j]->no++;
break;
}
}
if(j==k)
{
struct stu* temp=(struct stu*)(malloc(sizeof(struct stu)));
strcpy(temp->name,nam);
temp->no=1;
data[k++]=temp;
}
}
}
qsort(data, k, sizeof(struct stu*),cmpfunc);
for(int i=0 ; i<k ; i++)
{
printf("%s %d\n",data[i]->name,data[i]->no);
}
return 0;
}
如果我给出输入为
5
abcd
abcd
fgh
fgr
fgh
输出运行失败
最佳答案
除了 <cstdio>
,您的代码看起来更像 C 而不是 C++。也许你打算使用 <stdio.h>
, 注意针对 casting malloc
的各种警告,检查返回值并使用 C 编译器,但这个问题被标记为 C++。在 C++ 中有更明智的习语,例如:
-
std::string
而不是char*
/char[]
. -
std::cin
/std::cout
而不是scanf
/printf
. -
std::vector
而不是struct stu* data[1000]
. -
size_t
而不是int
用于数组索引和遍历数组。 -
new
/delete
/unique_ptr
而不是malloc
/free
.
using namespace std;
struct stu {
string name;
int no;
stu() {
}
};
int cmpfunc(const stu *p, const stu *q) {
return p->name < q->name;
}
int main(int argc, char** argv) {
size_t n;
cin >> n;
vector<stu*> data;
for (size_t i = 0; i < n; i++)
{
string nam;
cin >> nam;
if (i == 0)
{
auto* temp = new stu();
temp->name = nam;
temp->no = 1;
data.push_back(temp);
}
else
{
int j;
for (j = 0; j < data.size(); j++)
{
if(data[j]->name == nam)
{
data[j]->no++;
break;
}
}
if (j == data.size())
{
auto* temp= new stu();
temp->name = nam;
temp->no = 1;
data.push_back(temp);
}
}
}
std::sort(data.begin(), data.end(), cmpfunc);
for (int i = 0; i < data.size(); i++)
{
cout << data[i]->name << data[i]->no << endl;
delete data[i];
}
return 0;
}
关于c++ - 在 C++ 中使用 qsort 时运行失败错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51688898/