How add objects dynamically
This is the question :
How to do IT Right ?
IT = add objects dynamically (mean create class structures to support that)class Branch
{
Leaves lv; //it should have many leaves!!
}
class Tree
{
Branch br; //it should have many branchs!!!
}
Now a Non-Working Example (neither is c++ !!, but I try to draw the idea)
class Branch
{ 开发者_JAVA百科
static lv_count;
Leaves lv; //it should have many leaves!! (and should be some pointer)
public:
add(Leave lv)
{
lv[lv_count] = lv;
lv_count ++ ;
}
}
class Tree
{
static br_count;
Branch br; //it should have many branchs!!! (and should be some pointer)
Tree
public:
add(Branch br)
{
br[br_count] = lv;
br_count ++ ;
}
}
this is for example, reaching a stupid approach:
class Branch
{
static count;
Leaves l[1000]; //mmm i don't like this
//...
}
class Tree
{
static count;
Branch b[1000]; //mmm i don't like this
//...
}
I would like to know the formal normal way for doing this, Thanks!!!!!!
std::vector is the thing, you are looking for, I guess...
class Tree
{
std::vector<Branch> branches;
};
Vectors are the generic solution. However you shiould look at memory allocation before you start using libraries code such as vectors -- e.g., C++ new, calloc, malloc, thread local memory etc... Each STL container has it's own algorithmic complexities and studying these will aid you in picking the right one
Discussion :
If you want something to grow and you don't have the space for it.... well you have to realloc() or put algorithmically. Acquire a bigger memory buffer and copy the old buffer into it at the correct index offsets. This is what vector does behind the scenes; of-course vector just does this very well by (this is implementation specific) growing using the linear function (2x). growing in this way means it has more memory than it needs, which means that data added to the vector in the future won't cause an immediate reallocation.
However, I must add that this is very inefficient, you can almost always avoid the cost of copying things around. Vector's main use is for contiguous memory regions, you can almost always improve on vector by using linked data structures, perhaps in a binary tree for searching on a key :D
精彩评论