• 9
• 11
• 9
• 20
• 12

Correct container, or typdef for an array.

This topic is 4029 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

Recommended Posts

I’m looking for a simple boost or stl container or combination of containers that can hold a dynamically allocated array of items. The container needs to hold a raw pointer to the array (for libraries that need raw access), the size of the array and overload [] operator for access by functions that don’t require raw access to the array. These are templates I’ve looked at so far and the limitations I’ve had with them. Std::vector <>, don’t think its possible to get access to the raw array pointer Boost::array<>, not intended for dynamic allocation boost::shared_array<>, no size() function Its simple enough to role my own class to handle this but I’d rather ask and see if there is a right way of doing it. I need the raw pointer for handing the array to opengl functions and the like.

Share on other sites
Use std::vector. This works just fine:
    std::vector< Foo > foo;    Foo * pFoo = &foo[0];

Share on other sites
std::vector is probably your best bet.

I'm almost positive that vector's storage is guaranteed to be contiguous (I remember there was some discussion of this recently on the forums - I also remember reading an article online that confirmed this, but I can't produce a reference to it).

Although vector doesn't offer e.g. a data() function (not as far as I know, at least), you can acquire a pointer to the raw storage at any time as follows:
function_that_takes_a_raw_pointer(&v.front());
I've been using vector in this way with OpenGL functions for quite some time, and have never run into any problems. Keep in mind though that the address of the vector's internal storage may change when elements are added, inserted, and so on, so if you're storing this address in any way this should be taken into consideration.

[Edit: what John said.]

Share on other sites
Yeah I just need it for OpenGL functions and I know vector does cover most of what I need. So if I can get a raw pointer out of a vector that will work just fine, thanks.

Share on other sites
Quote:
 Original post by jykI'm almost positive that vector's storage is guaranteed to be contiguous (I remember there was some discussion of this recently on the forums - I also remember reading an article online that confirmed this, but I can't produce a reference to it).

Yep:

Quote:
 Working Draft, Standard for Programming Language C++ (c.2006)Section 23.2.5.1:The elements of a vector are stored contiguously, meaning that if v is a vector where T is some type other than bool, then it obeys the identity &v[n] == &v[0] + n for all 0 <= n < v.size().