Question

I'm stuck with this piece of code:

class MyObject
{
public:
    int value;
}

class MyClass
{
private:
    btAlignedObjectArray<MyObject*> m_objects;

public:

    int comp (MyObject *a, MyObject *b)
    {
        return calculateTheNewValue(a->value) < calculateTheNewValue(b->value);
    }

    void doSort()
    {
        m_objects.quickSort(comp);
    }

    //edit: this member function is needed to do the sorting
    int calculateTheNewValue(int v)
    {
            // do some calculation using other members variables, not necessarily m_objects
    }

};

It doesn't compile because comp is a non static member function.

comp cant be static, because it needs to access the member variable m_objects.

Also it would defeat the encapsulation of m_objects to have a static function and call it like this

MyClass::doSort(myClass.m_objects)

Edit

This is the declaration of btAlignedObjectArray

http://bulletphysics.org/Bullet/BulletFull/btAlignedObjectArray_8h_source.html

Line 365 has the declaration or quicksort

Was it helpful?

Solution

If you need to make comp into a binary function, then wrap it in a functor. If you can use C++11, then use a lambda:

m_objects.quickSort([&](MyObject * lhs, MyObject * rhs) {
        return this->comp(lhs,rhs)
    });

If you can't use C++11, then make a functor class with similar behavior.

struct compare
{
    MyObject & obj_;
    compare(MyObject& obj) :obj_(obj) {}

    bool operator()(MyObject * lhs, MyObject * rhs) const {
        return obj_.comp(lhs,rhs);
    }
};

...

void doSort()
{
    m_objects.quicksort(compare(*this));
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top