[英]Can I use vector sort function in my own struct? always compiler error
[Error] 'class std::vector' has no member named 'sort' which sort can use in struct and how to use? [错误] 'class std::vector' 没有名为 'sort' 的成员,可以在结构中使用哪个排序以及如何使用? sorry for my bad english.
对不起,我的英语不好。
typedef struct name
{
int x,y;
}name;
int main()
{
int n,m,i;
vector<name> a(10000);
while(scanf("%d%d",&n,&m)!=EOF)
{
if(n==0&m==0)
{
break;
}
a.clear();
for(i=0;i<n;i++)
{
scanf("%d",&a[i].x);
a[i].y=a[i].x%m;
}
a.sort();
for(i=0;i<n;i++)
{
printf("%d\n",a[i].x);
}
}
return 0;
}
vector
doesn't have a sort
function. vector
没有sort
function。 Instead, use std::sort
, and implement an operator<
for your struct.相反,请使用
std::sort
,并为您的结构实现operator<
。
struct name
{
int x,y;
bool operator<( const name &other ) const {
return x < other.x; // modify to whatever sorting conditions you need
}
};
Then for calling sort, do然后调用排序,做
std::sort( a.begin(), a.end() );
Since std::vector
has no sort()
member function, you should use std::sort
using the third argument as the sorting predicate.由于
std::vector
没有sort()
成员 function,您应该使用std::sort
使用第三个参数作为排序谓词。 By doing so, you are not changing the internals of the struct
you are sorting by adding an operator <
:通过这样做,您不会通过添加
operator <
来更改要排序的结构的内部struct
:
#include <algorithm>
#include <vector>
struct name
{
int x,y;
};
int main()
{
std::vector<name> a(10000);
// assuming you want to sort by x-coordinate
std::sort(a.begin(), a.end(), [](name& n1, name& n2) { return n1.x < n2.x; });
}
You can also create a separate lambda function:也可以单独创建 lambda function:
#include <algorithm>
#include <vector>
struct name
{
int x,y;
};
int main()
{
std::vector<name> a(10000);
auto comp = [](name& n1, name& n2) { return n1.x < n2.x; };
// assuming you want to sort by x-coordinate
std::sort(a.begin(), a.end(), comp);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.