Search code examples
c++stdvectorstdstringdynamic-allocation

std::string in std::vector?


I've already have some problems with std::vector inside std::vector if the internal vectors are redimensionned. I would like to know if it is perfectly secure to have a std::vector<std::string> (because the internal strings can be redimensionned) or std::vector<std::string*> is better ?


Solution

  • This question is most likely consequence of the misconception that looks vector the same as arrays.

    It is true that an array must contain elements of equal type and static size, as it is true that vector can be resized, but the static sizeof(vector<X>) does not depend on the run-time size of it. vector<vector<X> > contains internally just the pointer (plus some other descriptive data) to the dynamically allocated array of vector<X> each of which in turn contains just the pointer to its own dynamically allocated array of X.

    The arrays are in fact made by the same elements, of the same size.