C ++ pointer to vector
I need to insert elements into a pointer to a vector. I wrote the following code, but it gives a segmentation fault. Can someone point out what the errors are in this code or how we can do it as an alternative.
int main()
{
vector<int> *te;
te->push_back(10);
cout<<te->size()<<endl;
return 0;
}
source to share
vector<int> *te;
te->push_back(10);
You pointed a pointer to vector
; you haven't initialized it yet to point to a valid chunk of memory. You need to plot a new vector using new
.
vector<int> *te = new vector<int>();
However, you shouldn't do this. There are very few reasons to maintain a pointer to a vector, and you've just made it completely ineffective at managing its own internal memory.
Read a little about RAII . It is a technique used to manage dynamically allocated memory across the lifetime of an object. vector
uses this method to clean up internal, dynamically allocated storage when it goes out of scope.
Maintaining a pointer to a vector prevents it from working correctly by relying on what you call delete
yourself, essentially negating one major advantage of using vector
over an array in the first place.
source to share
you must first allocate space for the pointer before you can start using it.
vector<int> *te = new vector<int>();
insert this line into your code right after vector<int> *te;
note that
If you were trying to access an already defined vector with a pointer, you wouldn't need to allocate space for the pointer.
For example:
vector<int> foo={1,2,3,4,5};
vector<int> * te=&foo;
te->push_back(6); // its legal.
source to share