当我们将数组传递给函数,实际上会传递一个指针。
将向量传递给函数,将创建向量的副本。例如,我们可以在下面的程序中看到,由于函数具有副本,因此在函数内部所做的更改不会反映在外部。
// C++ program to demonstrate that when vectors
// are passed to functions without &, a copy is
// created.
#include
using namespace std;
// The vect here is a copy of vect in main()
void func(vector vect)
{
vect.push_back(30);
}
int main()
{
vector vect;
vect.push_back(10);
vect.push_back(20);
func(vect);
// vect remains unchanged after function
// call
for (int i=0; i
输出:
10 20
在大向量的情况下,上述传递方式也可能会花费很多时间。因此,引用作为参考是一个好主意。
// C++ program to demonstrate how vectors
// can be passed by reference.
#include
using namespace std;
// The vect is passed by reference and changes
// made here reflect in main()
void func(vector &vect)
{
vect.push_back(30);
}
int main()
{
vector vect;
vect.push_back(10);
vect.push_back(20);
func(vect);
for (int i=0; i
输出:
10 20 30
如果我们不希望函数修改向量,则可以将其作为const引用传递。
// C++ program to demonstrate how vectors
// can be passed by reference with modifications
// restricted.
#include
using namespace std;
// The vect is passed by constant reference
// and cannot be changed by this function.
void func(const vector &vect)
{
// vect.push_back(30); // Uncommenting this line would
// below error
// "prog.cpp: In function 'void func(const std::vector&)':
// prog.cpp:9:18: error: passing 'const std::vector'
// as 'this' argument discards qualifiers [-fpermissive]"
for (int i=0; i vect;
vect.push_back(10);
vect.push_back(20);
func(vect);
return 0;
}
输出:
10 20
要从最佳影片策划和实践问题去学习,检查了C++基础课程为基础,以先进的C++和C++ STL课程基础加上STL。要完成从学习语言到DS Algo等的更多准备工作,请参阅“完整面试准备课程” 。