多态中如何使用函数指针?
我希望能够使用多态性中的函数指针对数组进行排序。更不用说,我这样做只是为了看看事情是如何运作的等等。
I want to be able to sort an array out using function pointers in polymorphism. Not to mention, am only doing this to see how things work and so forth.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是一个简单的通用排序接口,通过该接口实现的插入排序,以及一些演示其用法的测试代码:
您可能还想看看 C 标准库的 qsort() 函数,它也使用函数指针比较器,但与上面相比有些限制。特别是,它假设您正在对连续数组进行排序,并且如果您有指向元素或其成员的指针,那么这些指针将被破坏(但上面的接口允许您修复 swap() 中的指针)。
下面是如何使用 qsort() 接口的示例,以及使用与 qsort() 相同接口的插入排序实现:
Here's a simple generic sorting interface, an insertion sort implemented through that interface, and some test code that demonstrates its use:
You might also want to take a look at the qsort() function of the C standard library, which too uses a function pointer comparator, but is somewhat limited to compared to the above. In particular, it assumes you're sorting a continuous array, and if you have pointers to elements or their members, those will be broken (but the above interface allows you to fix pointers in swap()).
Here's an example for how to use the qsort() interface, and also an insertion sort implementation that uses the same interface as qsort():