c++ - 为什么指针在对二维数组进行排序时不能正常工作?
问题描述
我使用此代码,但运行错误。它对某些数据进行了正确排序,但其余数据未正确排序。我想知道这段代码的错误在哪里,为什么?
#include<iostream>
using namespace std;
const int row=4;
const int col=4;
int main()
{
int mat[][col]={{1,2,3,4},{2,8,4,1},{3,5,7,8},{7,6,6,5}};
int arr[row][col];
cout<<" first "<<endl;
for(int i=0;i<row;i++){
for(int j=0;j<col;j++){
cout<<mat[i][j]<<" ";
}
cout<<endl;
}
for(int i=0;i < row;i++){
for(int j=i+1;j <= col;j++){
if(*(*(mat + 0) + i) >= *(*(mat + 0) + j)){
temp= *(*(mat + 0) + i);
*(*(mat + 0) + i) = *(*(mat + 0) + j);
*(*(mat + 0) + j) = temp;
}
}
}
cout<<" after arrangement "<<endl;
for(int i=0;i<row;i++){
for(int j=0;j<col;j++){
cout<<mat[i][j]<<" ";
}
cout<<endl;
}
return 0;
}
解决方案
目前尚不清楚您想要的排序规则是什么,但是,假设需要任何合理一致的排序,也许您会接受将数组转换为一维数组或指针并使用标准排序(如 qsort 或 std)以这种方式排序::sort ... 是否会导致未定义的行为或数组打包规则是否确保它始终被明确定义 - 如果您相信后者,那么这可能是您的答案。
推荐阅读
- c# - 如何将参数传递给计时器事件
- c# - 如何控制 iOS 的 PDF 文件的页面
- ios - Cordova 通用链接可在 iOS 模拟器中使用,但不适用于开发/产品构建
- php - 购物车中的 Woocommerce 自定义图像产品缩略图
- r - 按单列分组时使用 .SD 和 fwrite 生成的空 data.table 消息
- database - 需要提供数据库密码才能在运行时运行进化 - Play + Slick
- sql - 如何将缺失值的汇总结果设为零
- tcl - TclInvalidateStringRep() 不应该重置长度吗?
- css - CSS Grid/Flex:两列宽度相同,一列具有自动宽度
- javascript - 无法用字符串数组编写突变