函数返回值vector
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
vector <int> ret_vecInt()
{
vector <int> vecInt(5, 10);
return vecInt;
}
int main()
{
vector <int> vecIntTemp(5, 10);
vecIntTemp = ret_vecInt();
return 0;
}
函数是正确的!!ret_vecInt()返回的不是局部变量吗? 如果返回数组的是错的!这是为什么呢?求解
[解决办法]
会拷贝的
代价比较大
[解决办法]
返回的值是一个指针,在函数里面这个指针指向的是数组,但是函数运行结束之后空间会销毁,指针所指向的空间不存在
[解决办法]
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int ret_vecInt(vector <int> &list)
{
list.clear();
list.push_back(...); // 或者其他的赋值
return 0;
}
int main()
{
vector <int> vecIntTemp(5, 10);
ret_vecInt(vecIntTemp);
return 0;
}