0

私はダイクストラのアルゴリズムを実装しており、STLの「priority_queue」を使用してコーディングプロセスを高速化したいのですが、C ++でコーディングしようとする試みではよくあることですが、言語を理解していないために速度が低下しています。この例はhttp://www.cplusplus.com/reference/stl/priority_queue/priority_queue/で見つかりましたが、次のことを理解していません。

// constructing priority queues
#include <iostream>
#include <queue>
using namespace std;

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

  priority_queue<int> first;
  priority_queue<int> second (myints,myints+4);
  priority_queue< int, vector<int>, greater<int> > third (myints,myints+4);

  // using mycomparison:
  priority_queue< int, vector<int>, mycomparison > fourth;

  typedef priority_queue<int,vector<int>,mycomparison> mypq_type;
  mypq_type fifth (mycomparison());
  mypq_type sixth (mycomparison(true));

  return 0;
}

具体的には、「bool operator()(const int&lhs、const int&rhs)const」が私をつまずかせています。残りは大丈夫です。演算子のオーバーロードだと思いますが、「operator()」は私には意味がありません。どんな助けでもいただければ幸いです。

4

3 に答える 3

2

基本的に、operator()オーバーロードできる「単なる」別の演算子であるため、演算子のオーバーロードについて知っていることはすべて適用されます。たとえば、関数の呼び出しに使用するのと同じ構文でオブジェクトに適用できるため、便利です。

MyClass f;
f(); // i.e. f.operator()();

そうは言っても、ファンクターなどについてはそれ以外にも多くのことが言えます。詳細については、ファンクター/関数オブジェクトをGoogleで検索することをお勧めします。ここに1つのリンクがあります:

http://en.wikipedia.org/wiki/Function_object

上記のコードでpriority_queueは、キューに入れたものを並べ替えるために使用する比較ファンクターを取ります。最初のキュー(fifth)は通常の順序を使用します。2番目のキュー(sixth)は逆の順序を使用します。

于 2012-11-18T03:01:06.620 に答える
1

これは関数呼び出し演算子であり、次のように使用できます。

mycomparison mycomp;  //defines an object
mycomp(1,2);  // invokes operator()(int,int)
于 2012-11-18T03:02:39.570 に答える
0
bool operator () ( const int &, const int & );

これは、のオーバーロードである関数であり、operator()2つの整数を受け取り、ブール値を返します。const値を変更できないことを意味します。定数の略です。

于 2012-11-18T03:01:36.650 に答える