【问题标题】:std::vect sorting with member variable使用成员变量的 std::vector 排序
【发布时间】:2013-08-13 01:30:38
【问题描述】:

我被这段代码卡住了:

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 是一个非静态成员函数。

comp 不能是静态的,因为它需要访问成员变量 m_objects。

另外,它会破坏 m_objects 的封装以拥有一个静态函数并像这样调用它

MyClass::doSort(myClass.m_objects)

编辑

这是btAlignedObjectArray的声明

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

第 365 行有声明或quicksort

【问题讨论】:

  • comp 不需要对 m_objects 进行任何访问,因为您已经传递了应该相互比较的对象。您确定示例完整吗?
  • @j_schultz 抱歉,我遗漏了代码的重要部分,可能是咖啡太多(或太少)。 calculateTheNewValue() 是进行排序所需的成员函数
  • 显示btAlignedObjectArray::quickSort的声明。
  • 如果 calculateTheNewValue 不引用 m_objects,comp 和 calculateTheNewValue 可以是静态的。
  • @lulyon calculateTheNewValue 计算引用其他成员变量的值,我必须进行编辑以澄清

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


【解决方案1】:

如果您需要将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));
}

【讨论】:

  • 我使用的是 Xcode 4.6,它无法识别 [&](x,y){ ...} 语义,我会尝试仿函数方法
  • 顺便说一句,它是怎么调用的,它是一种作为参数传递的代码块
  • @rraallvv:你的意思是那个语法叫什么?它被称为lambda
  • @rraallvv:顺便说一句,我不使用 XCode,但我很确定它支持 C++11,你只需要启用它。检查这个:stackoverflow.com/questions/4574246/can-i-use-c11-with-xcode
  • lambda 方法有效,Xcode 在其他文件中显示了一些其他错误,但我可以尝试仅为这个启用 c++11
猜你喜欢
  • 1970-01-01
  • 2012-06-05
  • 1970-01-01
  • 2021-07-08
  • 2022-01-03
  • 2020-09-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多