I want to sort points_vec vector as shown in the pseudocode below. I want to sort this vector, by a coordinate value like x or y or z
class A{
  std:vector<double*> points_vec;
  void doSomething();
}
Then, in method A::doSomething, I want sort this vector: 
void A::doSomething() {
    std::sort(points_vec.begin(), points_vec.end(), sortPoints());
}
Can someone please show me syntax for the sortPoints() method.. Preferably I want it to be a method of class A. this post creates a struct to do this, not sure if I should create a similar struct within the class. Is there another way to handle this?
thanks
The simplest way is to provide a functor which is used by the sort algorithm to compare two values. You can write like this:
struct Compare
{
  bool operator()(double* first, double* second) const
 {
   //Compare points here
 }
};
And use like:
std::sort(p.begin(), p.end(), Compare());
EDIT for comment by OP: Yes, this sample code compiles fine:
class A
{
public:
    struct c
    {
        bool operator()(int a, int b) const
        {
            return a < b;
        }
    };
};
int main()
{
    std::vector<int> a1;
    a1.push_back(2);
    a1.push_back(1);
    std::sort(a1.begin(), a1.end(), A::c());
    return 0;
}
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With