使用STL对用户输入数组进行排序的错误有什么解决方案吗?

Is there any solution of the error of sorting user input array using STL?

本文关键字:错误 什么 解决方案 排序 STL 用户 输入 数组 使用      更新时间:2023-10-16

我的代码是:

#include<bits/stdc++.h>
#include<stdio.h>
using namespace std;
struct Interval
{
int init,last;
};
bool compare(Interval a,Interval b)
{
return (a.init < b.init);
}
int main()
{
int t,i,j;
int a[1000];
cin >> t;
for( j=0;j<t;++j){
for(i=0;i<t;i++)
{
cin >> a[i];        
}   
} 
sort(a,a+t,compare);
for( j=0;j<t;++j)
for(i=0;i<t;i++) 
{
cout<<a[i]<<" ";
}
cout<<"n";
return 0;
}

下面这条线的解决方案是什么?

sort(a,a+t,compare);

问题就在这里

bool compare(Interval a,Interval b)
{
return (a.init < b.init);
}

compare比较Interval对象

int a[1000];
sort(a,a+t,compare);

您正在尝试对int数组进行排序。

int数组或Interval数组进行排序,但要保持一致。compare函数必须与要排序的数组匹配。

您正在尝试对int a[1000];进行排序,这是一个int数组,而不是一个Interval数组。如果这确实是你的意图,那么你不需要谓词(compare函数(进行排序。您只需使用为int提供的默认operator<即可。这意味着您的代码可能只是:

std::sort(std::begin(a), std::begin(a) + t);
相关文章: