gpt4 book ai didi

c++ - 排序数组并匹配其他数组并得到错误

转载 作者:行者123 更新时间:2023-12-02 10:57:42 25 4
gpt4 key购买 nike

我正在尝试编写一个程序,在其中编写诸如姓名,分钟和秒钟之类的人的信息。我需要按时间对人进行排序。我不明白如何对分钟进行排序,也不会丢失其他数组序列的订单名称和秒数。他们只是站在原地不动。我也收到错误,因为排序有问题

#include <iostream>
#include <algorithm>
#include <string>
using namespace std;

struct people{
string name;
int min;
int sec;
};
int main()
{
int temp;
struct people z[6];
for(int i=0; i<6; i++)
{
cin>>z[i].name;
cin>>z[i].min;
cin>>z[i].sec;
}
sort(z.min,z.min +6);
cout<<endl;

for(int i=0; i<6; i++)
{
cout<<z[i].name<<" "<<z[i].min<<" "<<z[i].sec<<endl;
}
return 0;
}


I am getting this error:
error: request for member 'min' in 'z', which is of non-class type 'people [6]'

最佳答案

std::sort()需要两个迭代器作为参数-第一个是要排序的序列的初始位置,第二个是最终位置。这就是为什么您的代码无法编译的原因。

为了对数组进行排序,您必须在类/结构中定义一个operator <,或者提供一个比较函数作为sort()的第三个参数。

您可以在结构体人员中定义运算符<,如下所示:

bool operator < (const people &p)
{
return min < p.min;
}

然后像下面这样调用和校准:
sort(z, z + 6);

或者,您可以按以下方式定义函数comp(在struct people定义之后):
bool comp(const people &p1, const people &p2) { return (p1.min < p2.min); }

然后像这样调用sort():
sort(z, z + 6, comp);

关于c++ - 排序数组并匹配其他数组并得到错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56622395/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com