64,653
社区成员
发帖
与我相关
我的任务
分享
void printArryV1(int ai[][4]){
for (auto &row : ai){
for (auto col : row){
cout << col;
}
}
}
void main(){
int a[][4] = { { 1, 2, 2, 1 }, {1,1,1,1} };
printArryV1(a);
}
mic@mac ~/work/dashen$ c++ foo.cpp -std=c++0x
foo.cpp:4:22: error: cannot build range expression with array function parameter 'mtx' since parameter with array type 'int [2][4]' is treated as pointer type 'int (*)[4]'
for (auto &row : mtx) {
^~~
foo.cpp:3:22: note: declared here
void printArryV1(int mtx[2][4]) {
^
1 error generated.
看到mtx初始化为pointer类型。
重点看Page195:数组传递参数方式:1.数组引用行参,2.指向数组首元素的指针
=====================================================================
#include <iostream>
template<typename T>
void printArryV1(T& mtx) {
for (auto& row : mtx) {
for (auto col : row){
std::cout << col << " ";
}
std::cout << std::endl;
}
}
int main(int argc, char * argv[]) {
int arr[][4] = { { 1, 2, 2, 1 }, {1,1,1,1} };
printArryV1(arr);
return 0;
}
#include <iostream>
void printArryV1(int (&mtx)[2][4]) {
for (auto &row : mtx) {
for (auto col : row){
std::cout << col;
}
}
}
int main(int argc, char * argv[]) {
int arr[2][4] = { { 1, 2, 2, 1 }, {1,1,1,1} };
printArryV1(arr);
return 0;
}
编译通过,多维数组那章还要再看下,类型声明还不熟。#include <iostream> void printArryV1(int (&mtx)[2][4]) { for (auto &row : mtx) { for (auto col : row){ std::cout << col; } } } int main(int argc, char * argv[]) { int arr[2][4] = { { 1, 2, 2, 1 }, {1,1,1,1} }; printArryV1(arr); return 0; }
语法问题 void printArryV1(int (&a)[2][4])
http://en.cppreference.com/w/cpp/language/range-for说: range_expression - any expression that represents a suitable sequence (either an array or an object for which begin and end member functions or free functions are defined, see below) or a braced-init-list.
int a[][4] = { { 1, 2, 2, 1 }, {1,1,1,1} };for (auto &row : a){
for (auto col : row){
cout << col;
}
}
如果不是函数传参的话,直接在主函数内,范围for语句完全可以通过,这是怎么回事