作者:手机用户2502914387 | 来源:互联网 | 2022-12-04 11:44
我有一个表格矩阵pMat[M][N]
(其中M
和N
变量,因此,来自用户的输入).我想使用内置std::sort
函数对二维数组的元素进行排序.
例如,请考虑以下数组:
5 9 6
8 1 3
7 2 4
它应该输出为:
1 2 3
4 5 6
7 8 9
以下是我为此目的编写的代码:
#include
#include
int main() {
int M, N, **pMat;
std::cin >> M >> N;
pMat = new int* [M];
for (int i=0; i> pMat[i][j];
}
}
std::sort(&pMat[0][0], (&pMat[0][0])+(M*N));
for (int i=0; i
我基于以下理解编写了上面的代码:
数组C++
存储在连续的内存位置
std::sort(add1,add2)
对存储器位置中存在的所有元素进行排序 [add1,add2)
上面的代码没有给出正确的输出.例如,当提供以下输入时:
4 3
13 2 1
4 5 6
7 8 9
10 11 12
它显示以下输出:
0 0 0
5 6 13
7 8 9
10 11 12
我该如何编写代码?我的理解在哪里错了?
(有关信息,我查看了以下答案:使用内置函数(或任何其他方法)在C++中对2D数组进行排序?,但它不回答我的查询)
1> Galik..:
一种方法是创建一个连续(可排序)内存的大数组,然后通过第二个指针数组访问该数组作为子数组数组.
第二个数组只包含一个指针列表,每个指针指向较大的指针内的不同子数组.
像这样的东西:
int M, N;
std::cin >> M >> N;
// one big array of actual data
// (an array of contiguous sub-arrays)
std::vector v(M * N);
// array of pointers to sub-arrays within the actual data
std::vector pMat;
// point the pointers at the actual data
// each pointer pointing to the relevant sub-array
for(int i = 0; i > pMat[i][j];
// sort the actual data
std::sort(std::begin(v), std::end(v));
// look at the data through the sub-array pointers
for(int i = 0; i
注意:我曾经std::vector
管理过我的数组,但它也适用于使用new[]
和delete[]
(不推荐)创建的内置数组.
编辑:添加.
或者(更好)你可以创建一个类,它将数据存储在一个大的连续块中,并使用如下的数学偏移访问不同的子数组:
template
class two_dee_array
{
public:
two_dee_array(std::size_t M, std::size_t N): v(M * N), stride(N) {}
T& operator()(std::size_t M, std::size_t N)
{ return v[(M * stride) + N]; }
T const& operator()(std::size_t M, std::size_t N) const
{ return v[(M * stride) + N]; }
std::size_t col_size() const { return stride; }
std::size_t row_size() const { return v.size() / stride; }
auto begin() { return std::begin(v); }
auto end() { return std::end(v); }
auto begin() const { return std::begin(v); }
auto end() const { return std::end(v); }
auto cbegin() const { return std::cbegin(v); }
auto cend() const { return std::cend(v); }
private:
std::vector v;
std::size_t stride;
};
int main()
{
int M, N;
std::cin >> M >> N;
two_dee_array v(M, N);
for(int i = 0; i > v(i, j);
std::sort(std::begin(v), std::end(v));
for(int i = 0; i