1

コードの重複をできるだけ避けたい。次のようなクラスがあるとします。

class T {
    int val;
    bool operator < (const T& right) const { return val < right.val; }
}

このように std::sort() を呼び出せるようにしたいのですが、

std::sort( SomeContainer.begin(), SomeContainer.end(), FuncAdaptedFromOp );

これは、StackOverflow での最初の質問です。ご容赦ください。

編集

問題は、クラスが複数のbool T::Compare (const T& right)機能を持つ可能性があることです。やはりアダプターが欲しいです。この例を見て、

class Edge {
    Vertex u, v;
    bool CompareSrc (const Edge& right) const { return u < right.u; }
    bool CompareDest (const Edge& right) const { return v < right.v; }
}

source で並べ替えたい場合もあればVertex、destination で並べ替えたい場合もありますVertex。これが可能かどうかを知りたいだけです。

4

3 に答える 3

2

3 番目のパラメーターを指定しない場合は、< 演算子が使用されます。

http://www.cplusplus.com/reference/algorithm/sort/

「要素は、最初のバージョンでは operator< を使用して比較され、2 番目のバージョンでは comp を使用して比較されます。」

于 2012-04-07T07:15:03.140 に答える
1

STLファンクターを複製するだけですstd::less http://www.cplusplus.com/reference/std/functional/less/

template <class T> struct less : binary_function <T,T,bool> {
  bool operator() (const T& x, const T& y) const
    {return x<y;}
};

少ない例:

#include <iostream>
#include <functional>
#include <algorithm>

struct my_struct {
   int a;
   bool operator< (const my_struct &s) const {
      return a < s.a;
   }
};

int main() {
   my_struct array[10];

   for (int i = 0; i < 10; ++i)
      array[i].a = 10 - i;

   std::sort(array, array + 10, std::less<my_struct>());

   for (int i = 0; i < 10; ++i)
      std::cout << array[i].a << ", ";
}

あなたはそれを書く必要はありません。アルゴリズムstd::sortには2つのバージョンがあります。

template <class RandomAccessIterator>
  void sort ( RandomAccessIterator first, RandomAccessIterator last );

template <class RandomAccessIterator, class Compare>
  void sort ( RandomAccessIterator first, RandomAccessIterator last, Compare comp );

最初のバージョンは、クラスが提供する場合に使用できますoperator <(同等)。2番目のバージョンは、使用したくない場合operator <、または存在しない場合に使用されます。

少ない例:

#include <iostream>
#include <functional>
#include <algorithm>

struct my_struct {
   int a;
   bool operator< (const my_struct &s) const {
      return a < s.a;
   }
};

int main() {
   my_struct array[10];

   for (int i = 0; i < 10; ++i)
      array[i].a = 10 - i;

   std::sort(array, array + 10);

   for (int i = 0; i < 10; ++i)
      std::cout << array[i].a << ", ";
}

例でも同じ結果になります。

また、他のファンクターを使用して、などのソートアルゴリズムの動作を変更することもできますstd::greater

于 2012-04-07T07:20:42.040 に答える
1
using namespace std::placeholders;
std::sort(SomeContainer.begin(), SomeContainer.end()
    // or use &Edge::CompareDest if you want that instead
    , std::bind(&Edge::CompareSrc, _1, _2) );

std::bindただし、C++ 11 であるため、使用したいboost::bind場合があります (この場合、前の using ディレクティブを使用しないでください) またはbind実装に TR1 がある場合は from TR1 を使用する必要があります。それ以外の場合は、独自のファンクターをハンドロールすることをお勧めします。

于 2012-04-07T08:17:49.963 に答える