c++中常用的vector容器作为参数时,有三种传参方式,分别如下(为说明问题,用二维vector):
- function1(std::vector<std::vector<int> > vec),传值
- function2(std::vector<std::vector<int> >& vec),传引用
- function3(std::vector<std::vector<int> >* vec),传指针
注意,三种方式分别有对应的const形式,不在此讨论。
三种方式对应的调用形式分别为:
- function1(vec),传入值
- function2(vec),传入引用
- function3(&vec),传入地址
三种方式的效果分别为:
- 会发生拷贝构造
- 不会发生拷贝构造
- 不会发生拷贝构造
验证程序:
1 #include <iostream>
2 #include <vector>
3
4 using namespace std;
5
6 void function1(std::vector<std::vector<int> > vec)
7 {
8 cout<<"-----------------------------------------"<<endl;
9 //打印vec的地址
10 cout<<"function1.&vec:"<<&vec<<endl;
11 //打印vec[i]的地址(即第一层vector的地址)
12 cout<<"function1.&vec[i]:"<<endl;
13 for(int i=0;i<2;i++)
14 cout<<&vec[i]<<endl;
15 //打印vec的各元素地址
16 cout<<"function1.&vec[i][j]:"<<endl;
17 for(int i=0;i<2;i++)
18 {
19 for(int j=0;j<3;j++)
20 cout<<&vec[i][j]<<" ";
21 cout<<endl;
22 }
23 cout<<"---------------------------"<<endl;
24 //打印vec的各元素值
25 cout<<"function1.vec[i][j]:"<<endl;
26 for(int i=0;i<2;i++)
27 {
28 for(int j=0;j<3;j++)
29 cout<<vec[i][j]<<" ";
30 cout<<endl;
31 }
32 }
33 void function2(std::vector<std::vector<int> >& vec)
34 {
35 cout<<"-----------------------------------------"<<endl;
36 //打印vec的地址
37 cout<<"function2.&vec:"<<&vec<<endl;
38 //打印vec[i]的地址(即第一层vector的地址)
39 cout<<"function2.&vec[i]:"<<endl;
40 for(int i=0;i<2;i++)
41 cout<<&vec[i]<<endl;
42 //打印vec的各元素地址
43 cout<<"function2.&vec[i][j]:"<<endl;
44 for(int i=0;i<2;i++)
45 {
46 for(int j=0;j<3;j++)
47 cout<<&vec[i][j]<<" ";
48 cout<<endl;
49 }
50 cout<<"---------------------------"<<endl;
51 //打印vec的各元素值
52 cout<<"function2.vec[i][j]:"<<endl;
53 for(int i=0;i<2;i++)
54 {
55 for(int j=0;j<3;j++)
56 cout<<vec[i][j]<<" ";
57 cout<<endl;
58 }
59
60 }
61 void function3(std::vector<std::vector<int> > *vec)
62 {
63 cout<<"-----------------------------------------"<<endl;
64 //打印vec的地址
65 cout<<"function3.&vec:"<<vec<<endl;
66 //打印vec[i]的地址(即第一层vector的地址)
67 cout<<"function3.&vec[i]:"<<endl;
68 for(int i=0;i<2;i++)
69 cout<<&(*vec)[i]<<endl;
70 //打印vec的各元素地址
71 cout<<"function3.&vec[i][j]:"<<endl;
72 for(int i=0;i<2;i++)
73 {
74 for(int j=0;j<3;j++)
75 cout<<&(*vec)[i][j]<<" ";
76 cout<<endl;
77 }
78 cout<<"---------------------------"<<endl;
79 //打印vec的各元素值
80 cout<<"f