解決:std::sort的比較函式,切記僅使用小於或大於,不要使用小於等於或大於等於。即所謂的“ strict weak ordering”,也就是說,如果a==b,則返回的應該是false,如果返回的是true,則會出上面的錯
這個問題是標準庫sort實現導致的
參考https://blog.csdn.net/qq_35097289/article/details/104648601
class testOperator { public: int value=0; int value2=0; void setV(int v) { value = v; } void setV2(int v2) { value2 = v2; } bool operator <=(const testOperator& other) const { if (other < *this) { return false; } return true; } bool operator <(const testOperator& other) const { if (this->value == other.value) { return this->value2 < other.value2; } return this->value < other.value; } }; bool compareTestOperator(const testOperator& t1, const testOperator& t2) { return t1 <= t2; //不能使用<=,如果容器元素中有相等的,就會導致crash } int main() { { testOperator t1; testOperator t2; t2.setV(10);//當前沒問題,註釋掉這一句就會crash std::vector < testOperator > vec = {t1, t2}; std::sort(vec.begin(), vec.end(),compareTestOperator); std::cout << vec.size() << std::endl; }