Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sorting vector with 3D points by a coordinate value -- syntax

Tags:

c++

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

like image 760
memC Avatar asked Feb 20 '10 08:02

memC


1 Answers

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;
}
like image 66
Naveen Avatar answered Nov 08 '22 11:11

Naveen