A problem I’m working on involves a large tree structure. Initially I was creating the tree by newing new nodes and attaching them to their parent node and such. This was taking an awful long time. A friend suggested instead I forgo the dynamic memory allocation and structure the tree as an array with offsets to child words. I’ve not done this before and so I have some questions about what actually happens.
Here’s the ultra basic, no safety checks on anything example:
struct DataStructure
{
std::vector<Entry> mCollection;
};
struct Entry
{
char mValue;
std::vector<unsigned int> mOffsetCollection; //a vector of indexes that are offsets to other entries.
};
I’m curious about what happens as I add more data to this structure. If I added
DataStructure d;
Entry entry;
entry.mValue = 'a';
d.push_back(entry);
.
.
.//add some more entries...
.
.
//now suppose I add a bunch of offsets to these various entries in my array.
Entry& firstEntry = d.at(0);
firstEntry.mOffsetCollection.push_back(4);
firstEntry.mOffsetCollection.push_back(9);
firstEntry.mOffsetCollection.push_back(32);
..
So the size of this first Entry is increasing. What exactly happens? I just ran through through a small example and it seemed to work fine. The other entries in the data structure were unaffected. I was initially concerned that perhaps if the size of the structure became large it would run into the next item in the array but I suppose that isn’t happening. It makes me realize that I don’t really know what is going on behind the scenes. Is the vector<Entry> in DataStructure d having to reallocate memory?
You’re not using dynamic allocation, but the vector class is. The internal
vector<int>is storing its variable-length array externally to the Entry object that you’re putting in the outer vector.