【问题标题】:Static variable and virtual function in a class to implement the predicate for sort()类中的静态变量和虚函数实现 sort() 的谓词
【发布时间】:2014-07-31 16:49:45
【问题描述】:

使用静态变量和虚函数在 sort() 函数中实现谓词,用于多态类对象排序。这个解决方案有效吗?

下面的例子:

// Here we've got virtual function that return a static variable
// and each derived class has a separate unique static

class Base {
    protected:
        virtual const int &GET_ID const { return BASE_ID; }
    private:
        static const int BASE_ID = 0;
}

class Derived : public Base {
    private:
        const int &GET_ID const { return DERIVED_ID; }
        static const int DERIVED_ID = 1;
}

class Derived2 : public Base {
    private:
        const int &GET_ID const { return DERIVED2_ID; }
        static const int DERIVED2_ID = 2;
}


// We can then construct a predicate for the sort function to
// sort a list of polymorphic object

bool compare (Base *base1, Base *base2) {
    return base1->GET_ID() < base2->GET_ID();
} 

std::sort(containerOfBasePtr.begin(), containerOfBasePtr.end(), compare);

我知道这可以通过使用非静态受保护成员来完成,但它需要为每个对象分配更多内存。

【问题讨论】:

  • 你最好不要使用全部大写的标识符,除非你想花无数的时间来解决一些奇怪的错误
  • 在需要常量时使用静态常量成员是完全可以的。 (按多态类型排序可能不太好,为什么需要它?)
  • 这只是一个挑战,我想有一天我可能会遇到这样的问题。我对 OOP 还是很陌生,所以我什么都不知道。
  • 您可以通过使用type_index 省去在每个类中编写GET_ID 的麻烦——也就是说,如果您不需要类之间的特定相对顺序。

标签: c++ sorting object static


【解决方案1】:

“高效”是一个相对术语。但如果你不希望有任何额外的内存使用,那么使用虚拟函数或type_index 是我能想到的唯一选择。

另一方面,如果我们对问题上下文有更多了解,也许可以用完全不同的方式解决这个问题。一种可能的替代方法是将不同的对象存储在完全不同的容器中,由 unordered_map 索引。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-20
    相关资源
    最近更新 更多