【发布时间】:2015-04-30 11:25:21
【问题描述】:
我正在尝试通过使用函数来更改向量元素内的数据。碰巧元素在函数内部发生了变化。如何将更改保留在函数之外?我必须使用指针吗?
代码:
#include <iostream>
#include <vector>
using namespace std;
void populate( int size_, vector<int> pop)
{
//Set the vector's size and populate the vector
pop.resize(size_);
for(int i = 0; i<3 ; i++)
{
pop[i] = i;
}
}
int main()
{
vector<int> vec;
int size = 3;
populate(size, vec);
for(vector<int>::iterator it = vec.begin(); it != vec.end(); ++it)
{
cout << *it << endl;
}
}
cout 的输出应该是:0 1 2
但它是空的。
【问题讨论】:
-
你的函数看起来应该是构建并返回一个向量,而不是把一个向量作为参数。
-
最近我试图解释一些与朋友有关的事情,我编造了this example。当你运行它时,你可以看到你传递的对象是如何被复制到一个局部变量中的,并且一旦函数返回,这个局部变量就会被删除。
标签: c++ function pointers vector