動態分配的vector指針
vector<int> *get_num(int n)
{
vector<int> *pv = new vector<int>(n+1);
int i , x;
for(i = 0; i < n; i++)
{
cin>>x;
<span style="background-color: rgb(255, 0, 0);">(*pv)[i] = (x);
</span> }
return pv;
}
如果是動態分配的vector指針,那麼當爲vector中插入元素時只能用數組的方法(上述代碼紅色),如果用.push_back()函數的方法,就會出錯,不知道爲什麼?
使用shared_ptr的vector指針
shared_ptr<vector<int>> get_num(int n)
{
shared_ptr<vector<int>> pv = make_shared<vector<int>>();
int i , x;
for(i = 0; i < n; i++)
{
cin>>x;
<span style="color:#ff0000;">(*pv).push_back(x);</span>
}
return pv;
}
如果是使用shared_ptr的vector指針,那麼當爲vector中插入元素時只能用.push_back的方法(上述代碼紅色),如果用數組插入的方法,就會出錯,正好和動態分配的vector指針相反 , 不知道爲什麼?