qsort在C ++中不适用于哪些类型? [英] What kinds of types does qsort not work for in C++?

查看:104
本文介绍了qsort在C ++中不适用于哪些类型?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

std::sort使用std::swap交换元素,而std::swap使用复制构造函数和赋值运算符,从而确保在交换值时获得正确的语义.

std::sort swaps elements by using std::swap, which in turn uses the copy constructor and assignment operators, guaranteeing that you get correct semantics when exchanging the values.

qsort通过简单地交换元素的基础位来交换元素,而忽略与要交换的类型相关的任何语义.

qsort swaps elements by simply swapping the elements' underlying bits, ignoring any semantics associated with the types you are swapping.

即使qsort不了解您要排序的类型的语义,但对于非平凡的类型,它仍然可以很好地工作.如果我没记错的话,它将适用于所有标准容器,尽管它们不是POD类型.

Even though qsort is ignorant of the semantics of the types you are sorting, it still works remarkably well with non-trivial types. If I'm not mistaken, it will work with all standard containers, despite them not being POD types.

我想qsort在类型T上正确工作的前提是T是/triviallyly//.在我的头顶上,唯一不容易移动的类型是那些带有内部指针的类型.例如:

I suppose that the prerequisite for qsort working correctly on a type T is that T is /trivially movable/. Off the top of my head, the only types that are not trivially movable are those that have inner pointers. For example:

struct NotTriviallyMovable
{
    NotTriviallyMovable() : m_someElement(&m_array[5]) {}

    int m_array[10];
    int* m_someElement;
};

如果对NotTriviallyMovable的数组进行排序,则m_someElement最终将指向错误的元素.

If you sorted an array of NotTriviallyMovable then the m_someElements would end up pointing to the wrong elements.

我的问题是:qsort还有哪些其他类型的类型不起作用?

My question is: what other kinds of types do not work with qsort?

推荐答案

这对于具有指向相关"对象的指针的类型也不起作用.这样的指针具有许多与内部"指针相关的问题,但是要精确地证明相关"对象是什么要困难得多.

This doesn't work either for types that have pointers to "related" objects. Such pointers have many of the issues associated with "inner" pointers, but it's a lot harder to prove precisely what a "related" object is.

一种特定类型的相关"对象是带有反向指针的对象.如果将对象A和B进行位交换,并且A和C指向彼此,则之后B将指向C,而C将指向A.

A specific kind of "related" objects are objects with backpointers. If object A and B are bit-swapped, and A and C pointed to each other, then afterwards B will point to C but C will point to A.

这篇关于qsort在C ++中不适用于哪些类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆