3

私のコードの基本構造は

class Foo{
  vector<string> _lines;
  vector<int> _n;
  public:
  ...
  bool Comp(int i, int j){
    return something that depends on _lines;
  }
  ...
  void doSomething(){
    std::sort(_n.begin(), _n.end(), Comp);
  }
  ...
};

しかし、私は得る

error: no matching function for call to 
‘sort(std::vector<unsigned int>::iterator, 
std::vector<unsigned int>::iterator, <unresolved overloaded function type>)

ベクトルをコピーせずにこの問題を解決するにはどうすればよいですか? (これらのベクトルは、正確には 17179508 文字列という非常に大きな文字列であるため)。

4

3 に答える 3

4

std::sortこの場合、2 つの int を取るバイナリ述語が必要です。メンバー関数は暗黙的な最初のパラメーターを受け取るため、全部Foo::Compで 3 つのパラメーターを受け取ります。非メンバー関数または静的メンバー関数を渡すことができますが、これらのいずれもFooのデータ メンバーにアクセスできません。簡単な方法は、メンバー関数の最初のパラメーターにstd::bindバインドするために使用することです。this

#include <functional> // for std::bind
#include <vector>
#include <algorithm>

class Foo{
  vector<string> _lines;
  vector<int> _n;
 public:
  ...

  bool Comp(int i, int j){
    return something that depends on _lines;
  }
  ...
  void sort(){
    using namespace std::placeholders;
    std::sort(_n.begin(), _n.end(), std::bind(Comp, this, _1, _2));
  }
  ...
};
于 2013-06-03T16:28:38.980 に答える