I use the following method to get an allocated memory space without worrying about how to reclaim the allocated resource.
#include <vector>
using namespace std;
int _tmain(int argc, _TCHAR* argv[])
{
vector<int> vecInts;
for(int iInd=0; iInd<10; i++)
vecInts.push_back(iInd);
int* pInt = &vecInts[0]; // Is this a good method?
// now can I use pInt to modify the value of the vecInts?
// I will NOT resize the vector and just simply manipulate the values inside
return 0;
}
However, I am not sure whether such a method is a good one or not.
Thank you
Yes, that's fine given the precautions you mention (and other obvious ones, like not using a pointer into a vector that's gone out of scope etc.). The pointer will be valid and invalidated in the exact same way that an iterator into the container would be.
That's a fine method. The memory will be freed automatically when the vector goes out of scope. In modern STL implementations vector
has a method data()
which returns the pointer to the start of the memory, which is equivalent to &v[0]
, but looks much cleaner.
This approach also has the nice property that each element is set to 0 (or default-constructed if it's an object).
For efficiency, if you know the length of the vector in advance, you can supply it as a constructor argument. Then all the memory will be allocated once. E.g.
vector<char> buffer(bufSize);
fread(buffer.data(), 1, buffer.size(), file);
And, like you mention in the comment, be aware that buffer.data()
will change if the buffer is resized, and deallocated when it goes out of scope.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With