![](/img/trans.png)
[英]How can can I sort a vector of pointed-to values using std::sort()?
[英]how can i sort my struct by x coordinate using std::sort
這是我的結構:
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);
};
然后我填上我的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;
}
我已經嘗試過了
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);
刪除!=
檢查。 如果x
值相等,則會給程序帶來不確定的行為,因為該函數將無法return
語句。
bool sorter(Pont const& lhs, Pont const& rhs) {
return lhs.getX() < rhs.getX();
}
如果x
值相等,則它將返回false
,這應該這樣做。
另外,您對std::sort
調用不正確。 假設pontok
是大小為N
的點的數組,則需要執行以下操作:
std::sort(pontok, pontok + N, &sorter);
std::sort
帶有一個迭代器范圍,該范圍指向要排序的序列的開頭和結尾。 您正在傳遞數組的兩個元素。
當X坐標相等時,您的sorter
函數似乎什么也不返回,這是您的意思嗎?
可能很簡單:
bool sorter(Pont const& lhs, Pont const& rhs) {
return lhs.getX() < rhs.getX();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.