当我们 将数组传递给函数 A. 指针 实际上是通过了。但是,要传递向量,有两种方法:
null
- 传递值
- 参考
当 矢量 传递给函数时,将创建向量的副本。然后在函数中使用向量的新副本,因此,对函数中向量所做的任何更改都不会影响原始向量。
例如,我们可以在程序下面看到,函数内部所做的更改不会反映在外部,因为函数有一个副本。
示例(按值传递):
CPP
// C++ program to demonstrate that when vectors // are passed to functions without &, a copy is // created. #include <bits/stdc++.h> using namespace std; // The vect here is a copy of vect in main() void func(vector< int > vect) { vect.push_back(30); } int main() { vector< int > vect; vect.push_back(10); vect.push_back(20); func(vect); // vect remains unchanged after function // call for ( int i = 0; i < vect.size(); i++) cout << vect[i] << " " ; return 0; } |
输出
10 20
通过值传递保持原始向量不变,并且不修改向量的原始值。然而,在向量较大的情况下,上述传球方式也可能需要很多时间。因此,通过参考传递是一个好主意。
示例(通过引用传递):
CPP
// C++ program to demonstrate how vectors // can be passed by reference. #include <bits/stdc++.h> using namespace std; // The vect is passed by reference and changes // made here reflect in main() void func(vector< int >& vect) { vect.push_back(30); } int main() { vector< int > vect; vect.push_back(10); vect.push_back(20); func(vect); for ( int i = 0; i < vect.size(); i++) cout << vect[i] << " " ; return 0; } |
输出
10 20 30
通过引用传递可以节省大量时间,并加快代码的实现。
注: 如果我们不希望函数修改向量,我们可以将其作为 康斯特 也请参考。
CPP
// C++ program to demonstrate how vectors // can be passed by reference with modifications // restricted. #include<bits/stdc++.h> using namespace std; // The vect is passed by constant reference // and cannot be changed by this function. void func( const vector< int > &vect) { // vect.push_back(30); // Uncommenting this line would // below error // "prog.cpp: In function 'void func(const std::vector<int>&)': // prog.cpp:9:18: error: passing 'const std::vector<int>' // as 'this' argument discards qualifiers [-fpermissive]" for ( int i = 0; i < vect.size(); i++) cout << vect[i] << " " ; } int main() { vector< int > vect; vect.push_back(10); vect.push_back(20); func(vect); return 0; } |
输出
10 20
本文由 卡尔蒂克 .如果你喜欢GeekSforgek,并想贡献自己的力量,你也可以使用 写极客。组织 或者把你的文章寄去评论-team@geeksforgeeks.org.看到你的文章出现在Geeksforgeks主页上,并帮助其他极客。如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END