我在使用STL排序函数对派生类进行排序时遇到问题.
示例 -
标题:
vector<AbstractBaseClass *> *myVector;
Run Code Online (Sandbox Code Playgroud)
在ImpL中:
sort(myVector->begin(), myVector->end(), compareBy);
Run Code Online (Sandbox Code Playgroud)
比较器:
bool MyClass::compareBy(AbstractBaseClass& a, AbstractBaseClass& b) {
return (a->someMethod() < b->someMethod());
}
Run Code Online (Sandbox Code Playgroud)
编辑:这个问题适用于使用STL排序抽象类的一般用法(我没有发布跟踪转储).如果它已经不明显了,我会说它没有办法可以编译为打印.相反,我问(给定数据结构)人们通常会如何对这个玩具抽象类进行排序.
感谢您的快速解答,我相信你们已经钉了它们!
得到了StackOverFlow!
一个例子:
struct Abstr {
virtual int some()const == 0;
virtual ~Abstr() = default;
};
bool abstrSmaller( const Abstr* a1, const Abstr* a2 ) {
return a1->some() < a2->some();
}
int main() {
vector<Abstr*> v;
sort( v.begin(), v.end(), abstrSmaller );
}
Run Code Online (Sandbox Code Playgroud)
static或free函数.vector's元素作为参数,即指针,而不是引用.const函数,因此它可以接受const参数.