Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ -- Get internal pointer to a vector

Tags:

c++

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

like image 617
q0987 Avatar asked Mar 09 '11 05:03

q0987


2 Answers

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.

like image 155
Tony Delroy Avatar answered Sep 24 '22 02:09

Tony Delroy


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.

like image 36
DS. Avatar answered Sep 27 '22 02:09

DS.