我有一個奇怪的問題,也許我錯過了一些明顯的東西,但我無法解決。C++無效比較器
這裏是拋出斷言C++代碼:
int compareByX(const Vector2D &a, const Vector2D &b)
{
if (a.x < b.x) // if i put a.x > b.x nothing changes
return -1;
return 1;
}
int main(int argc, char *argv[])
{
double pts[6] = { 5, 34, 3, 54, 10, 34 };
std::vector<Vector2D> points;
for (int i = 0; i < 6; i += 2)
points.push_back({ pts[i],pts[i + 1] });
std::sort(points.begin(), points.end(), compareByX);
}
什麼情況是,第一點(3,54)抵靠(5,34)進行測試,然後反之亦然。 在這一點上,引發了assert(無效比較器)。但正如我所看到的,它返回-1的權利,因爲3小於5,然後返回1,因爲5大於3 ...
你能告訴我這有什麼問題嗎?
'sort'預計比較函數返回TRUE;('1')或'FALSE'('0' )。你覺得'-1'發生了什麼?這種實現'compareByX'的方法如何:{return a.x
BoBTFish
[這個'std :: sort'引用](http://en.cppreference.com/w/cpp/algorithm/sort)應該是有幫助的。 –
現在我明白了,謝謝!以爲我正在使用qsort:/ – deight