2017-02-05 122 views
2

我想排序一個std::vector包含自定義結構,其中每個都有自己的vectorint值。關鍵是我想根據內部intvector的排序...即{1, 1, 2, 3, 4}小於{1, 2, 2, 3, 4},因爲vector中的第二個值。C++無效的比較排序向量的結構

在我看來,這將提供嚴格的弱排序,但運行時總會收到無效的比較器異常。我也試圖實現一個單獨的鍵功能作爲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()); 
} 
+2

必須是'INT main',不'無效main'。 –

回答

4

嘗試用

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}較小。

P.S:但你也可以使用operator<()爲載體

bool operator< (const AA& a1) const 
{ return this->AA_v < a1.AA_v; } 
+0

我沒有意識到你需要強制其他的假,我很驚訝我沒有碰到向量的運算符<()。 – incanus86