[英]Passing Arrays of any size to C++ functions
我知道您可以通過其他方式傳遞數組,例如:
returnType函數名(dataType數組[] [10])
但是,如果您不事先知道數組的大小,我會很感興趣。 我希望能夠將行數和列數作為參數傳遞。
如何將任意大小的數組傳遞給C ++函數? 我想按照以下方式做點事情:
void functionName(dataType array[][], int num_rows, int num_cols){
// ***Some operation such as printing the array's contents***
}
有三種解決方法:
template <std::size_t W, std::size_t H> void func(Type (&array)[W][H]) {}
兩種可能性:
使用向量的向量,那么您甚至不必將大小作為額外的參數傳遞:
void functionName( std::vector<std::vector<dataType>>);
使用模擬二維二維數組的一維數組:
void functionName( dataType [] array, int num_rows, int num_cols);
像這樣計算一維數組的索引:
int i = row_index * num_cols + column_index;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.