關於動態分配vector指針和使用shared_ptr的vector指針

動態分配的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指針相反 , 不知道爲什麼?


發佈了189 篇原創文章 · 獲贊 17 · 訪問量 19萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章