2017-06-13 4 views
0

私はクラス "PclProc"を持っており、std :: sortを使いたいと思います。std :: sortは同じクラスのメンバー関数を使用していますか?

同じクラスに比較関数を書くのは、この比較に同じクラスの変数である "in_ptr"が必要なためです。

しかし、私は次のように行ったように、エラーが常にある:STDに使用されている数子の

error: no matching function for call to ‘sort(std::vector::iterator, std::vector::iterator, )’ std::sort(cloud_indice.indices.begin(),cloud_indice.indices.end(),PclProc::MyCompare);

bool PclProc::MyCompare(int id1, int id2) 
{ 
    return in_ptr->points[id1].z<in_ptr->points[id2].z; 
} 


float PclProc::MedianZDist(pcl::PointIndices cloud_indice) 
{ 
    std::sort(cloud_indice.indices.begin(),cloud_indice.indices.end(),PclProc::MyCompare); 
    int size=cloud_indice.indices.size(); 
    float median_x,median_y; 
... 
+0

std :: sortは、通常のメンバー関数では機能しません。関数演算子(ファンクタ)、またはC++コンパイラがラムダ関数をサポートする場合はラムダ関数を使用できます。 [this one](https://stackoverflow.com/questions/37767847/stdsort-function-with-custom-compare-function-results-error-reference-to-non)のようなこれに関する先のスレッドがあります。 – rcgldr

+0

@rcgldrありがとう。私の状況はC++ 11は利用できません。したがって、ラムダ関数は使用できません。私は関数演算子のオーバーロードを知っています。しかし、あなたは私の特別な場合のために書く方法について私により多くのヒントを与えることができますか? – user7487638

答えて

0

例::ソート。ベクトルDはデータ、ベクトルIはDへのインデックスです。私はファンクタを使用してstd :: sortでDに従ってソートされます。 std :: sortはクラスlessthanのインスタンスを1つしか作成せず、すべての比較に対してその1つのインスタンスを使用します。

#include <algorithm> 
#include <cstdlib> 
#include <iostream> 
#include <iomanip> 
#include <vector> 

typedef unsigned int uint32_t; 

#define SIZE 16 

class example{ 
public: 
    std::vector<uint32_t> D; // data 
    std::vector<uint32_t> I; // indices 

example(void) 
{ 
    D.resize(SIZE); 
    I.resize(SIZE); 
    for(uint32_t i = 0; i < SIZE; i++){ 
     D[i] = rand()%100; 
     I[i] = i; 
    } 
} 

void displaydata(void) 
{ 
    for(size_t i = 0; i < SIZE; i++) 
     std::cout << std::setw(3) << D[I[i]]; 
    std::cout << std::endl; 
} 

class lessthan     // lessthan functor for std::sort 
{ 
public: 
const example &x; 
    lessthan(const example &e) : x(e) { } 
    bool operator()(const uint32_t & i0, const uint32_t & i1) 
    { 
     return x.D[i0] < x.D[i1]; 
    } 
}; 

void sortindices(void) 
{ 
    std::sort(I.begin(), I.end(), lessthan(*this)); 
} 
}; 

int main() 
{ 
example x; 
    x.displaydata(); 
    x.sortindices(); 
    x.displaydata(); 
    return 0; 
} 
関連する問題