【发布时间】:2020-09-12 01:25:40
【问题描述】:
我遇到this question 对整数数组的前两行进行排序,想到的明显方法是使用std::sort,因此我提出了如下解决方案:
int mat[][3] = { {4, 5, 3},
{6, 8, 7},
{9, 5, 4},
{2, 1, 3} };
std::sort(std::begin(mat[0]), std::end(mat[1])); //sprting the first two rows
您可以see here 工作,不会出现错误或警告。
同时 @Jarod42 pointed out that this is pedantically undefined behaviour 在 C++ 中,因为它们是两个不同数组的指针。
我倾向于这样做,因为在 C 中这将是一个很好的方法,(当然没有 std::sort、std::begin 和 std::end),使用类似的方法来访问数组,考虑到二维数组在 C 中的存储方式。
我们同意这是未定义的行为,but as @SergeBallesta remebered,几乎所有编译器都接受这种方法,所以应该使用它吗?
如果one uses a int(*mat)[3] pointer to array,这样使用std::sort 还是迂腐的UB?
//...
srand(time(0));
int(*mat)[3] = (int(*)[3])malloc(sizeof(int) * 4 * 3);
//or int(*mat)[3] = new int[4][3];
for(int i = 0; i < 4 ; i++)
for(int j = 0; j < 3; j++)
mat[i][j] = rand() % 9 + 1;
std::sort(std::begin(mat[0]), std::end(mat[1])); //sorting the first two rows
//...
【问题讨论】:
-
@anastaciu:可以检测到(至少在
constexprhere)。糟糕的是,没有好的选择。并且编译器会做预期的事情(如果编译器将其视为 UB(将代码删除为错误的执行路径),那么确实需要警告来解决问题)。