I am working on a project where I absolutly need to have data contiguous in memory. I want to store some (maximum 100) string (I don't know the actual size of each string). So I will create a vector of string of 100 elements.
std::vector<std::string> vect;
vect.reserve(100)
But a String can be of any size. So how does it work? Is my vector reallocated everytime I change a string? Or is a std::string simply like a pointer to the first character of the string like a char* would be for a C string?
Vectors are assigned memory in blocks of contiguous locations. When the memory allocated for the vector falls short of storing new elements, a new memory block is allocated to vector and all elements are copied from the old location to the new location. This reallocation of elements helps vectors to grow when required.
Use a vector for array-like storage of your strings. Example 4-6 offers a simple example. vector s follow array semantics for random access (they also do a lot more), so they are easy and familiar to use. vector s are just one of many sequences in the standard library, however; read on for more of this broad subject.
The elements of a vector are stored in a dynamically allocated block of memory; otherwise, the capacity of the vector could not increase. The vector object just holds a pointer to that block.
@user1145902: They are stored in memory like in an array, but that memory is not allocated in the stack (or wherever the string object is), but rather in a dynamically allocated buffer.
string
will be an instance of class string
and that instance will contain a char*
.string
objects in the vector will be in contiguous memory.string
will be in contiguous memorystd::allocator
for the stringsvector
or call shrink_to_fit
string
may change when you increase the size of the string
vector
will not be reallocated if you modify or remove one of the stringsstring
will be stored within the string
instead of another location pointed to by char*
The data in std::vector
is laid out contiguosly. However std::string
s implementation does not guarantee that the memory holding the character array is stored locally to the class itself. How could it? Like you said you don't know how large the string will be.
A lot of array like structures have a layout like follows:
class string
{
T * begin;
T * end;
T * capacity;
}
Which means that your vector of 100 strings will have 100 instances of a class layout that POINTS to the memory where the string is stored.
Now if you need to pack memory allocations as tightly as possible and still want to use std::string
you can write a custom allocator.
Maybe you can write the string data into a char array and have a second container that stores the lengths of each individual string + NULL terminator.
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