将子向量与 qsort 一起使用

Using Sub-Vectors With qsort

我写了一个答案 here to use qsort to sort an array-of-arrays. I could not use sort 因为它在 swap 操作中使用了赋值运算符。

我认为我的回答工作的规定是:

The type of the elements of the array must be a TrivialType, otherwise the behavior is undefined

所以我的问题是:int[2]是"TrivialType"吗?


提示这个问题的答案中的实际代码是:

int array[5][2] = { {20, 11}, {10, 20}, {39, 14}, {29, 15}, {22, 23} };
static const auto SIZE = size(*array);

qsort(array, size(array), sizeof(*array), [](const auto lhs, const auto rhs) {
    const auto first = reinterpret_cast<const int*>(lhs);
    const auto last = next(first, SIZE);
    const auto its = mismatch(first, last, reinterpret_cast<const int*>(rhs));

    if (its.first == last) {
        return 0;
    } else if (*its.first < *its.second) {
        return -1;
    } else {
        return 1;
    }});

是的,int[2] 是一个普通类型。从基本.types/9

... Scalar types, trivial class types (Clause [class]), arrays of such types and cv-qualified versions of these types ([basic.type.qualifier]) are collectively called trivial types. ...

int 是标量类型。

So my question is: Is int[2] a "TrivialType"?

是的,是的。

你可以很容易地检查这个,所有必要的工具都在手边 <type_traits>:

#include <type_traits>
#include <iostream>

int main() {
    int a[2];

    std::cout << "a is " << (std::is_trivial<decltype(a)>()?"":"non ") << "trivial" << std::endl;
}

产出

a is trivial

Live Demo

A int 是 [basic.fundamental] 的算术类型,算术类型也称为 [basic.types]/9

的标量类型

Arithmetic types (3.9.1), enumeration types, pointer types, pointer to member types (3.9.2), std::nullptr_-t, and cv-qualified versions of these types (3.9.3) are collectively called scalar types.

然后我们有

Scalar types, trivial class types (Clause 9), arrays of such types and cv-qualified versions of these types (3.9.3) are collectively called trivial types

强调我的

所以标量类型和标量数组都是普通类型

所有引用自 N3797 草案