我正在寻找 C++ 中的函数来打印由 C++ 中允许的各种机制创建的二维整数数组。请引用我在下面粘贴的代码中的注释,了解我用于创建二维整数数组的不同技术。
#include<iostream>
#define ROW 3
#define COL 4
using namespace std;
void printMatrix(int **mat)
{
cout<<"\n Printing Matrix : \n";
for(int i=0 ; i<=ROW-1 ; i++)
{
for(int j=0 ; j<=COL-1 ; j++)
cout<< *(*(mat+i)+j)<<" ";
cout<<endl;
}
cout<<endl;
}
int main()
{
// Method 1 - Creation of 2D Matrix using Square Braces
int mat1[][COL] = { {34,36,31,39},
{12,19,13,17},
{28,24,26,23}, };
// Method 2 - Creation of 2D Matrix using new operator
int **mat2 = new int*[ROW]();
for(int i=0 ; i<=ROW-1 ; i++)
mat2[i] = new int[COL]();
//printMatrix((int **)mat1);
//Uncommenting above line throws exception "Access Violation while reading location!"
printMatrix(mat2);
cin.get();
return 0;
}
printMatrix() 函数应该能够打印 mat1 和 mat2。 如何解决这个问题?
最佳答案
将您的函数设为模板函数可以解决问题:
template<typename T>
void printMatrix(T mat) {
cout<<"\n Printing Matrix : \n";
for(int i=0 ; i<=ROW-1 ; i++) {
for(int j=0 ; j<=COL-1 ; j++)
cout<< *(*(mat+i)+j)<<" ";
cout<<endl;
}
cout<<endl;
}
然而,这仅适用于 3x4 数组,因为您在宏定义中对维度进行了硬编码。
但是对于一般情况,您不能将具体的二维数组与堆分配的二维数组一样对待,因为除了类型不同之外,对于第一个,您可以获得维度信息,而对于第二个,则不能。因此,您必须区别对待它们。
例如,对于二维数组,您可以执行以下模板函数:
template<std::size_t N, std::size_t M>
void print_array(int (&A)[N][M]) {
for(std::size_t i(0); i < N; ++i) {
for(std::size_t j(0); j < M; ++j)
std::cout << A[i][j] << " ";
}
}
但是对于动态分配的数组,您需要它的维度来遍历它:
void print_array(int **a, std::size_t N, std::size_t M) {
for(std::size_t i(0); i < N; ++i) {
for(std::size_t j(0); j < M; ++j)
std::cout << A[i][j] << " ";
}
}
因此,对于任意维度的数组,您最终会得到以下通用函数来处理它们(即,您必须传递维度):
template<typename T>
void printMatrix(T mat, std::size_t N, std::size_t M) {
cout<<"\n Printing Matrix : \n";
for(int i = 0 ; i < N ; ++i) {
for(int j = 0 ; j < N; ++j)
cout<< *(*(mat+i)+j)<<" ";
cout<<endl;
}
cout<<endl;
}
但是,您可以使用 STL 容器,尤其是 std::vector<std::vector<int>>
替换代码中的二维数组和动态分配的二维数组。通过重载 operator<<
为此:
std::ostream& operator<<(std::ostream &out, std::vector<std::vector<int>> const&v) {
for(auto &&i : v) {
for(auto &&j : i) out << j << " ";
out << std::endl;
}
return out;
}
你可以打印你的 std::vector<std::vector<int>>
(例如,vv
)作为:
std::cout << vv << std::endl;
关于c++ - C++ 中用于打印由各种技术创建的二维整数数组的通用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33841529/