Dynamically allocated vector pointer
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;
}
If it is a dynamically allocated vector pointer, you can only use the array method (the above code is red) when inserting elements into the vector. If you use the .push_back () function method, you will get an error.
Vector pointer using shared_ptr
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;
}
If the vector pointer of shared_ptr is used, you can only use the .push_back method (the above code is red) when inserting elements into the vector. If you use the array insertion method, you will get an error. Know why?