std :: vector使用成员变量排序

时间:2013-08-13 01:30:39

标签: c++ sorting vector std member-functions

我坚持使用这段代码:

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
    }

};

它不能编译,因为comp是非静态成员函数。

可以是静态的,因为它需要访问成员变量m_objects。

此外,它会破坏m_objects的封装以具有静态函数并像这样调用它

MyClass::doSort(myClass.m_objects)

修改

这是btAlignedObjectArray的声明

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

第365行有声明或quicksort

1 个答案:

答案 0 :(得分: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));
}