在您的预期输出中,您排序的是行,因此您的标题不准确。
获取您提供的示例输出:
Live demo
int mat[][3] = { {4, 5, 3},
{6, 8, 7},
{9, 5, 4},
{2, 1, 3} };
给定 C 样式的 2D 数组,对前 2 行进行排序:
#include <algorithm>
//...
std::sort(std::begin(mat[0]), std::end(mat[0]));
std::sort(std::begin(mat[1]), std::end(mat[1]));
要对整个数组进行排序,您可以使用循环:
for(size_t i = 0; i < sizeof(mat) / sizeof(mat[0]); i++) //deduce the number of rows
std::sort(std::begin(mat[i]), std::end(mat[i]));
输出:
3 4 5
6 7 8
9 5 4
2 1 3
如果您想使用 C++ 容器,比如推荐使用向量的向量,或者使用固定大小的数组 std::array:
Sample to sort the whole 2D vector(std::array同法)
std::vector<std::vector<int>> mat = {
{4, 5, 3},
{6, 8, 7},
{9, 5, 4},
{2, 1, 3}};
for(size_t i = 0; i < mat.size(); i++)
std::sort(std::begin(mat[i]), std::end(mat[i]));
如您所见,这是一种更友好的方法,因为 C++ 容器有一个成员来存储自己的大小。
输出:
3 4 5
6 7 8
4 5 9
1 2 3