0 引言
在使用数组和vector作为函数的参数进行参数传递并希望得到值的回传时,由于不知道怎么写数组函数形参的引用形式,一直采用vector的引用形式。但是,刚刚测试了一下,发现数组作为参数本身就是指针,根本不需要采用引用形式把值回传啊,把测试结果写下来。
1 关于数组作为函数参数的值传递问题——数组和容器的对比
数组直接作为形参进行传递,容器(以vector为例)以引用形式作为形参
1. 函数代码
1void arrayTest(double myarray[3]){ 2 for(int i=0; i<3; ++i){ 3 myarray[i] = i+1; 4 } 5} 6 7void vectorTest(vector<int>& myVector){ 8 for(int i=0; i<3; ++i){ 9 myVector[i] = i+1; 10 } 11}
2. 测试代码
1void arrayAndVectorTest(){ 2 double myarray[3] = {0,0,0}; 3 arrayTest(myarray); 4 cout << "array test" <<endl; 5 for(int i=0; i<3;i++){ 6 cout << "第" << i << "个数 = " << myarray[i] << endl; 7 } 8 vector<int> myVector{0,0,0}; 9 vectorTest(myVector); 10 cout << "vector test" <<endl; 11 for(auto it = myVector.begin(); it != myVector.end(); ++ it) 12 cout << "第" << it -myVector.begin() + 1 << "个数 = " << *it << endl; 13}
3. 测试结果如下

两种方法均实现了值的回传.
4. 数组直接作为形参进行传递,容器(以vector为例)以引用形式作为形参
1void vectorTest(vector<int> myVector){ 2 for(int i=0; i<3; ++i){ 3 myVector[i] = i+1; 4 } 5}

此时,数组实现了值回传,但是容器没有实现值回传。