0
class Star {
 public:
  // The distance between this star to the Earth.
  double distance() const { return sqrt(x_ * x_ + y_ * y_ + z_ * z_); }

  bool operator<(const Star& s) const { return distance() < s.distance(); }

  int ID_;
  double x_, y_, z_;
};



priority_queue<Star, vector<Star>> max_heap;

最後の行を見てください。これは、priority_queue max_heap の初期化です。c++ const Compare& を無視する理由。だろうと思った

priority_queue<Star, vector<Star>, Star> max_heap;

以下のように異なって見えますが、私は理解しています。

class mycomparison
{
  bool reverse;
public:
  mycomparison(const bool& revparam=false)
    {reverse=revparam;}
  bool operator() (const int& lhs, const int&rhs) const
  {
    if (reverse) return (lhs>rhs);
    else return (lhs<rhs);
  }
};

int main ()
{
  int myints[]= {10,60,50,20};

  std::priority_queue<int> first;
  std::priority_queue<int> second (myints,myints+4);
  std::priority_queue<int, std::vector<int>, std::greater<int> >
                            third (myints,myints+4);
  // using mycomparison:
  typedef std::priority_queue<int,std::vector<int>,mycomparison> mypq_type;

  mypq_type fourth;                       // less-than comparison
  mypq_type fifth (mycomparison(true));   // greater-than comparison

  return 0;
}

このページを読みました: http://www.cplusplus.com/reference/queue/priority_queue/priority_queue/

priority_queue コンストラクター パラダイムの決定的な定義を取得できません。

また、コンパレータとして「<」をオーバーロードすることがあるのはなぜですか。コンパレータとして「()」をオーバーロードすることがありますか? ありがとう

4

1 に答える 1

3

デフォルトの比較は、定義std::less< Star >した を呼び出すものです。operator <

テンプレート型パラメーターは、関数パラメーターと同様に、デフォルトの引数を持つことができます。デフォルトのコンテナ タイプであるstd::vector< Star >. 実際、宣言は次のように簡単に記述できます。

priority_queue<Star> max_heap;

また、コンパレータとして「<」をオーバーロードすることがあるのはなぜですか。コンパレータとして「()」をオーバーロードすることがありますか?

コンパレーターは常に Callable オブジェクト、つまり、関数または関数のようなオブジェクト (ファンクター) です。比較対象は、括弧付きの関数呼び出し表記を使用して渡されます。指定されたオーバーロードをファンクターのメンバーとしてアクセスできるようにstd::lessするアダプターです。bool operator< (T, T)operator()

たとえば、std::less実装方法は次のとおりです。

template< typename T >
struct less {
    bool operator () ( T const & lhs, T const & rhs ) const
        { return lhs < rhs; } // Calls Star::operator < ()
};

std::lessは実際にはオブジェクト型であり、そのようなオブジェクトは実際にはpriority_queue. それoperator()が比較をするものです。あなたへの呼び出しoperator <はこのように行われます。

于 2014-07-24T02:05:23.120 に答える