vector作为参数的三种传参方式
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),传入地址
三种方式的效果分别为:
- 会发生拷贝构造
- 不会发生拷贝构造
- 不会发生拷贝构造
验证程序
#include<iostream> #include<vector> using namespace std; void function1(vector<vector<int> > vec) { cout << "-----------------------------------------" << endl; //打印vec的地址 cout << "function1.&vec:" << &vec << endl; //打印vec[i]的地址(即第一层vector的地址) cout << "function1.&vec[i]:" << endl; for (int i = 0; i < 2; i++) cout << &vec[i] << endl; //打印vec的各元素地址 cout << "function1.&vec[i][j]:" << endl; for (int i = 0; i < 2; i++) { for (int j = 0; j < 3; j++) cout << &vec[i][j] << " "; cout << endl; } cout << "---------------------------" << endl; } void function2(vector<vector<int> >& vec) { cout << "-----------------------------------------" << endl; //打印vec的地址 cout << "function2.&vec:" << &vec << endl; //打印vec[i]的地址(即第一层vector的地址) cout << "function2.&vec[i]:" << endl; for (int i = 0; i < 2; i++) { cout << &vec[i] << endl; } //打印vec的各元素地址 cout << "function2.&vec[i][j]:" << endl; for (int i = 0; i < 2; i++) { for (int j = 0; j < 3; j++) cout << &vec[i][j] << " "; cout << endl; } cout << "---------------------------" << endl; } void function3(vector<vector<int> > *vec) { cout << "-----------------------------------------" << endl; //打印vec的地址 cout << "function3.&vec:" << &vec << endl; //打印vec[i]的地址(即第一层vector的地址) cout << "function3.&vec[i]:" << endl; for (int i = 0; i < 2; i++) { cout << &vec[i] << endl; } //打印vec的各元素地址 cout << "function3.&vec[i][j]:" << endl; for (int i = 0; i < 2; i++) { for (int j = 0; j < 3; j++) cout << &(*vec)[i][j] << " "; cout << endl; } cout << "---------------------------" << endl; } int main() { //创建一个2x3的vector数组 vector<vector<int> > v(2, vector<int> (3,0)); for (int i = 0; i < 2; i++) { for (int j = 0; j < 3; j++) { v[i][j] = i + j; //0 1 2 1 2 3 } } //打印v的地址 cout << "&v:" << &v << endl; //打印v[i]的地址(即第一层vector的地址) cout << "&v[i]:" << endl; for (int i = 0; i < 2; i++) { cout << &v[i] << endl; } //打印v的所有元素的地址 cout << "&v[i][j]:" << endl; for (int i = 0; i < 2; i++) { for (int j = 0; j < 3; j++) { cout << &v[i][j] << " "; } cout << endl; } cout << "----------------------------------------" << endl; //打印v的各元素值 for (int i = 0; i < 2; i++) { for (int j = 0;j < 3;j++) { cout << v[i][j] << " "; } cout << endl; } function1(v); function2(v); function3(&v); return 0; }View Code
简而言之,vector的内部存储模型是这个样子(以main()函数中的v为例):
转载:http://www.cnblogs.com/xiaoxi666/p/6843211.html
标签:std,function1,cout,vector,三种,内存,vec From: https://www.cnblogs.com/kongyijin/p/17399564.html