我已經注意到,在gcc C11中,您可以將任何矩陣傳遞給函數fn(int row, int col, int array[row][col])
。如何翻譯我的下面放置(在一個鏈接到另一個stackoverflow答案)在C11程序到C++ 11程序?C++ 11中的二維矩陣是否與C11類似?
C - allocating a matrix in a function
正如你看到的,我可以傳遞給函數的靜態和動態分配的數組中的C11。在C++ 11中可能嗎?
我做了一個基於不同的計算器答案的示例程序,但所有函數都適用於array1,並且它們都不適用於array2,其中double array1[ROW][COL] = { { } }
和auto array2 = new double[ROW][COL]()
?
如何在C11 fn(int row, int col, int array[row][col])
中製作兩個陣列的功能?
#include <iostream>
#include <utility>
#include <type_traits>
#include <typeinfo>
#include <cxxabi.h>
using namespace std;
const int ROW=2;
const int COL=2;
template <size_t row, size_t col>
void process_2d_array_template(double (&array)[row][col])
{
cout << __func__ << endl;
for (size_t i = 0; i < row; ++i)
{
cout << i << ": ";
for (size_t j = 0; j < col; ++j)
cout << array[i][j] << '\t';
cout << endl;
}
}
void process_2d_array_pointer(double (*array)[ROW][COL])
{
cout << __func__ << endl;
for (size_t i = 0; i < ROW; ++i)
{
cout << i << ": ";
for (size_t j = 0; j < COL; ++j)
cout << (*array)[i][j] << '\t';
cout << endl;
}
}
// int array[][10] is just fancy notation for the same thing
void process_2d_array(double (*array)[COL], size_t row)
{
cout << __func__ << endl;
for (size_t i = 0; i < row; ++i)
{
cout << i << ": ";
for (size_t j = 0; j < COL; ++j)
cout << array[i][j] << '\t';
cout << endl;
}
}
// int *array[10] is just fancy notation for the same thing
void process_pointer_2_pointer(double **array, size_t row, size_t col)
{
cout << __func__ << endl;
for (size_t i = 0; i < row; ++i)
{
cout << i << ": ";
for (size_t j = 0; j < col; ++j)
cout << array[i][j] << '\t';
cout << endl;
}
}
int main()
{
double array1[ROW][COL] = { { } };
process_2d_array_template(array1);
process_2d_array_pointer(&array1); // <-- notice the unusual usage of addressof (&) operator on an array
process_2d_array(array1, ROW);
// works since a's first dimension decays into a pointer thereby becoming int (*)[COL]
double *b[ROW]; // surrogate
for (size_t i = 0; i < ROW; ++i)
{
b[i] = array1[i];
}
process_pointer_2_pointer(b, ROW, COL);
// allocate (with initialization by parentheses())
auto array2 = new double[ROW][COL]();
// pollute the memory
array2[0][0] = 2;
array2[1][0] = 3;
array2[0][1] = 4;
array2[1][1] = 5;
// show the memory is initialized
for(int r = 0; r < ROW; r++)
{
for(int c = 0; c < COL; c++)
cout << array2[r][c] << " ";
cout << endl;
}
//process_2d_array_pointer(array2);
//process_pointer_2_pointer(array2,2,2);
int info;
cout << abi::__cxa_demangle(typeid(array1).name(),0,0,&info) << endl;
cout << abi::__cxa_demangle(typeid(array2).name(),0,0,&info) << endl;
return 0;
}
爲什麼不只是傳遞像'vector>&'? –
Michael
2014-12-13 09:12:11
我知道這個模板解決方案。但如果我在我的程序中提到了這兩個數組,我想知道正確的答案。是否有可能將這兩個數組傳遞給相同的函數? – 42n4 2014-12-13 09:20:35
@ 42n4 - 爲什麼你需要爲這樣一個看似簡單的問題發佈所有這些代碼? 5行main()函數調用幾個虛擬函數是否足以傳遞您的觀點? – PaulMcKenzie 2014-12-13 09:28:44