我想交换矩阵中的两行。我的矩阵是一个分配的固体内存块。 我有一个指向矩阵行的指针数组。第一个指针指向这个大的分配块。其他指针指向不同的部分或这个块。用公用指针交换指向已分配内存的指针
如果我交换任何两行,除了第一个,它没关系。但我在第一排有问题。 我想这是因为指向第一行的指针与其他指针不同。但主要区别是什么?
#include <iostream>
int** allocateMatrix(int rows, int cols) {
// allocating array of pointers (rows)
int** matrix = new int*[rows];
// allocating one solid block for the whole matrix
matrix[0] = new int[rows*cols];
// setting the pointers for rows
for (int i = 1; i < rows; ++i) {
matrix[i] = matrix[i-1] + cols;
}
// fill the matrix with consecutive numbers
int k = 1;
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
matrix[i][j] = k;
k += 1;
}
}
return matrix;
}
void freeMatrix(int** matrix) {
delete[] matrix[0];
delete[] matrix;
}
int main() {
int n = 3;
int m = 3;
int** matrix = allocateMatrix(n, m);
// swap the first and the second line
int* tmp = matrix[0];
matrix[0] = matrix[1];
matrix[1] = tmp;
// print matrix (it is printing ok)
for (int i = 0; i < n; ++i) {
for (int j = 0; j < m; ++j) {
std::cout << matrix[i][j] << ' ';
}
std::cout << std::endl;
}
// problem is here
freeMatrix(matrix);
return 0;
}
创建一个矩阵类,其中包含一个'vector> data'成员,并实现一个交换函数,该函数在数据变量或其某行上调用'std :: swap'。 –
2014-09-28 16:41:17