在C++中,可以通过以下几种方法从函数中返回矩阵(或者称为数组):
#include <iostream>
// 返回指向矩阵的指针
int** createMatrix(int rows, int cols) {
int** matrix = new int*[rows];
for (int i = 0; i < rows; ++i) {
matrix[i] = new int[cols];
}
return matrix;
}
// 释放矩阵内存
void releaseMatrix(int** matrix, int rows) {
for (int i = 0; i < rows; ++i) {
delete[] matrix[i];
}
delete[] matrix;
}
int main() {
int rows = 3;
int cols = 3;
int** matrix = createMatrix(rows, cols);
// 使用矩阵
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
matrix[i][j] = i * cols + j;
std::cout << matrix[i][j] << " ";
}
std::cout << std::endl;
}
// 释放矩阵内存
releaseMatrix(matrix, rows);
return 0;
}
#include <iostream>
#include <vector>
// 定义矩阵结构体
struct Matrix {
std::vector<std::vector<int>> data;
int rows;
int cols;
};
// 创建矩阵
Matrix createMatrix(int rows, int cols) {
Matrix matrix;
matrix.rows = rows;
matrix.cols = cols;
matrix.data.resize(rows, std::vector<int>(cols));
return matrix;
}
int main() {
int rows = 3;
int cols = 3;
Matrix matrix = createMatrix(rows, cols);
// 使用矩阵
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
matrix.data[i][j] = i * cols + j;
std::cout << matrix.data[i][j] << " ";
}
std::cout << std::endl;
}
return 0;
}
#include <iostream>
#include <vector>
// 定义矩阵类
class Matrix {
public:
Matrix(int rows, int cols) : data(rows, std::vector<int>(cols)), rows(rows), cols(cols) {}
// 获取矩阵元素
int getElement(int row, int col) const {
return data[row][col];
}
// 设置矩阵元素
void setElement(int row, int col, int value) {
data[row][col] = value;
}
private:
std::vector<std::vector<int>> data;
int rows;
int cols;
};
// 创建矩阵
Matrix createMatrix(int rows, int cols) {
return Matrix(rows, cols);
}
int main() {
int rows = 3;
int cols = 3;
Matrix matrix = createMatrix(rows, cols);
// 使用矩阵
for (int i = 0; i < rows; ++i) {
for (int j = 0; j < cols; ++j) {
matrix.setElement(i, j, i * cols + j);
std::cout << matrix.getElement(i, j) << " ";
}
std::cout << std::endl;
}
return 0;
}
以上是在C++中从函数返回矩阵的几种常见方法。根据具体的需求和场景,选择合适的方法来实现。
领取专属 10元无门槛券
手把手带您无忧上云