1

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

4

1 回答 1

2

如果您需要将其制成comp二进制函数,则将其包装在函子中。如果您可以使用 C++11,请使用 lambda:

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

如果您不能使用 C++11,则创建一个具有类似行为的仿函数类。

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));
}
于 2013-08-13T02:30:23.283 回答