[英]C++ Invalid Comparator sorting Vector of Structs
我正在嘗試對包含自定義結構的std::vector
進行排序,每個結構都具有自己的int
值vector
。 關鍵是我想根據內部int
vector
的順序進行排序...因為第二個原因, {1, 2, 2, 3, 4}
{1, 1, 2, 3, 4}
小於{1, 2, 2, 3, 4}
vector
中的vector
。
在我看來,這將提供嚴格的弱排序,但是在運行它時,我始終會收到Invalid Comparator異常。 我也嘗試過實現一個單獨的鍵函數作為std::sort()
的第三個參數,但同樣的事情也會發生。
我究竟做錯了什么?
#include <iostream>
#include <algorithm>
#include <vector>
typedef struct AA {
std::vector<int> AA_v;
bool operator<(const AA& a1)const {
for (int i = 0; i < this->AA_v.size(); i++) {
if (this->AA_v[i] < a1.AA_v[i]) {
return true;
}
}
return false;
}
}AA;
void main(void) {
AA a1, a2, a3, a4;
a1.AA_v = { 1, 1, 3, 5, 4 };
a2.AA_v = { 1, 1, 2, 4, 5 };
a3.AA_v = { 0, 1, 3, 5, 4 };
a4.AA_v = { 1, 1, 3, 4, 5 };
std::vector<AA> AA_vector;
AA_vector.push_back(a1);
AA_vector.push_back(a2);
AA_vector.push_back(a3);
AA_vector.push_back(a4);
std::sort(AA_vector.begin(), AA_vector.end());
}
試試看
bool operator<(const AA& a1)const {
for (int i = 0; i < this->AA_v.size(); i++) {
if (this->AA_v[i] < a1.AA_v[i]) {
return true;
}
else if (this->AA_v[i] > a1.AA_v[i]) {
return false;
}
}
return false;
}
否則,對於您的代碼, {3, 1}
結果小於{1, 3}
並且也得出{1, 3}
小於{3, 1}
。
附言:但您也可以將operator<()
用於向量
bool operator< (const AA& a1) const
{ return this->AA_v < a1.AA_v; }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.