[英]how can i sort my struct by x coordinate using std::sort
here is my struct: 这是我的结构:
class Pont{
private:
int x, y;
public:
Pont( int x=0, int y=0);
int getX() const;
int getY() const;
void setX( int x );
void setY( int y );
void move( int nx, int ny);
};
and I fill my Pont type pontok : 然后我填上我的Pont型pontok:
while(n < N){
int x=(rand()%2000);
int y=(rand()%2000);
Pont p(x,y);
if(!letezike(p,n)){
pontok[n]=p;
++n;
}
and I've tried with this: 我已经尝试过了
bool sorter(Pont const& lhs, Pont const& rhs) {
if (lhs.getX() != rhs.getX())
return lhs.getX() < rhs.getX();
}
std::sort(pontok[0], pontok[N], &sorter);
Remove that !=
check. 删除
!=
检查。 It gives your program undefined behaviour if the x
values are equal because the function will not reach a return
statement. 如果
x
值相等,则会给程序带来不确定的行为,因为该函数将无法return
语句。
bool sorter(Pont const& lhs, Pont const& rhs) {
return lhs.getX() < rhs.getX();
}
If the x
values are equal, this will return false
, as it should do. 如果
x
值相等,则它将返回false
,这应该这样做。
Also, your call to std::sort
is incorrect. 另外,您对
std::sort
调用不正确。 Assuming pontok
is an array of points of size N
, you need to do: 假设
pontok
是大小为N
的点的数组,则需要执行以下操作:
std::sort(pontok, pontok + N, &sorter);
std::sort
takes an iterator range which point to the beginning and end of the sequence you want to sort. std::sort
带有一个迭代器范围,该范围指向要排序的序列的开头和结尾。 You were passing in two elements of your array. 您正在传递数组的两个元素。
Your sorter
function appears to return nothing when the X co-ordinates are equal, is that what you meant?! 当X坐标相等时,您的
sorter
函数似乎什么也不返回,这是您的意思吗?
It could be simply: 可能很简单:
bool sorter(Pont const& lhs, Pont const& rhs) {
return lhs.getX() < rhs.getX();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.