2017-02-05 5 views
2

std::vectorのカスタム構造体を含むソートしようとしています。それぞれの構造体にはvectorというintの値があります。重要な点は、 vectorの注文に基づいてソートすることです。つまり、vectorの2番目の値のために{1, 1, 2, 3, 4}{1, 2, 2, 3, 4}未満です。C++構造体の無効なコンパレータソートベクトル

これは厳密な弱い順序付けを提供すると思われますが、実行時に常に無効なコンパレータ例外が発生します。また、別のキー機能をstd::sort()の3番目のパラメータとして実装しようとしましたが、同じことが起こります。

私は間違っていますか?

#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

ためoperator<()を使用することができますが、 'int型main'、'無効ではないmain'でなければなりません。 –

答えて

4

{1, 3}より{3, 1}結果小さい、あなたのコードで、それ以外の場合は

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; 
} 

で試してみて、{1, 3}{3, 1}よりも小さいであることも事実つながります。

P.s:しかし、あなたはまた、ベクトル

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

もう一方を強制的にfalseにする必要があることはわかりませんでしたが、私はvectorの演算子<()に遭遇していなかったのに驚いています。 – incanus86

関連する問題