使用抽象类进行 STL 排序
我在使用 STL 排序函数对派生类进行排序时遇到问题。
示例 -
标头:
vector<AbstractBaseClass *> *myVector;
在 ImpL 中:
sort(myVector->begin(), myVector->end(), compareBy);
比较器:
bool MyClass::compareBy(AbstractBaseClass& a, AbstractBaseClass& b) {
return (a->someMethod() < b->someMethod());
}
编辑:这个问题面向使用 STL 对抽象类进行排序的一般用法(我不会发布跟踪转储)。如果它还不明显,我会说它根本不可能按照打印的方式进行编译。相反,我问的是(给定数据结构)人们通常如何对这个玩具抽象类进行排序。
感谢您的快速回答,我相信你们已经搞定了!
我很喜欢 StackOverFlow!
I'm having a problem sorting my derived classes with the STL sort function.
Example -
The header:
vector<AbstractBaseClass *> *myVector;
In the ImpL:
sort(myVector->begin(), myVector->end(), compareBy);
The comparator:
bool MyClass::compareBy(AbstractBaseClass& a, AbstractBaseClass& b) {
return (a->someMethod() < b->someMethod());
}
Edit: This question is geared toward general usage of sorting abstract classes with the STL (I'm not posting a trace dump). If its not apparent already, I'll say that there is no way in hell it can compile as printed. Rather, I'm asking (given the data structures) how one would typically sort with this toy abstract class.
Thanks for the quick answers, I believe you guys already nail'd it!
Got'a love StackOverFlow!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
示例:
An example:
static
or a free function.vector
's elements as argument, i.e. a pointer, not a reference.const
functions, so it can acceptconst
arguments.compareBy
不能是非静态成员函数(因为这需要编译器将隐式this
指针传递给该函数)。您可以将其设为静态成员、自由函数或函数对象。后者通常更好,因为它通常允许更好的优化(尽管在您的代码中,抽象惩罚可能会撤销这一点)。value_type
,这是一个AbstractBaseClass*
,而不是AbstractBaseClass&
。这看起来像下面这样:
您还可以使这个比较器成为您的类的私有成员,这样它就不会污染任何名称空间。
compareBy
must not be a non-static member function (since this would require the implicitthis
pointer to be passed to the function by the compiler). You can either make it a static member, a free function, or a function object. The latter is generally better, as it usually allows better optimization (although in your code the abstraction penalty might undo that anyway).value_type
, and that's anAbstractBaseClass*
, not anAbstractBaseClass&
.This would look like the following:
You can also make this comparator a private member of your class, so it doesn't pollute any namespace.