实现这一目标的一种方法是创建一个大的array连续(可排序)内存,然后将该数组作为子数组的数组通过一秒钟array的指针。
第二个数组仅包含一个指针列表,每个指针都指向较大数组中的不同子数组。
像这样的事情:
int M, N;
std::cin >> M >> N;
// one big array of actual data
// (an array of contiguous sub-arrays)
std::vector<int> v(M * N);
// array of pointers to sub-arrays within the actual data
std::vector<int*> pMat;
// point the pointers at the actual data
// each pointer pointing to the relevant sub-array
for(int i = 0; i < M; i++)
pMat.push_back(v.data() + (i * N));
// get the input, changing the actual data
// through the pointers
for(int i = 0; i < M; i++)
for(int j = 0; j < N; j++)
std::cin >> 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 < M; i++)
{
for(int j = 0; j < N; j++)
std::cout << pMat[i][j] << " ";
std::cout << '\n';
}
return 0;
Note: I used std::vector
管理我的数组,但它也可以与使用创建的内置数组一起使用new[]
and delete[]
(不建议)。
EDIT: To add.
或者 (好多了)您可以创建一个类,将数据存储在一个大的连续块中并访问不同的子数组使用这样的数学偏移:
template<typename T>
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<int> v;
std::size_t stride;
};
int main()
{
int M, N;
std::cin >> M >> N;
two_dee_array<int> v(M, N);
for(int i = 0; i < M; i++)
for(int j = 0; j < N; j++)
std::cin >> v(i, j);
std::sort(std::begin(v), std::end(v));
for(int i = 0; i < M; i++)
{
for(int j = 0; j < N; j++)
std::cout << v(i, j) << " ";
std::cout << '\n';
}
}