0

I have a class "PclProc" and I want to use std::sort.

I write a compare function in the same class because this comparing need the "in_ptr" which is a variable in the same class.

But as I did as following, there is always an error:

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;
...
user7487638
  • 151
  • 8
  • std::sort won't work with a normal member function. You can use a function operator (functor), or a lambda function if your C++ compiler supports lambda functions. There prior threads about this such as [this one](https://stackoverflow.com/questions/37767847/stdsort-function-with-custom-compare-function-results-error-reference-to-non) . – rcgldr Jun 13 '17 at 06:39
  • @rcgldr Thank you. My situation is C++11 is not available. So the lambda function cannot use. I know the function operator overload. But can you give me more hints about how to write for my special case? – user7487638 Jun 13 '17 at 15:08

1 Answers1

0

Example of a functor being used for std::sort. vector D is the data, vector I is the indices to D. I is sorted according to D with std::sort using the functor. std::sort only creates one instance of class lessthan, then uses that one instance for all of the compares.

#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;
}
rcgldr
  • 27,407
  • 3
  • 36
  • 61