Can i use vector as base data store for binary tree
C ++ has:
-
statically defined arrays -
T[constant]
- for which the dimension must be a compile-time constant, -
dynamically allocated arrays a la
new T[variable]
where size can change at runtime -
A standard library class
std::array<T, constant>
that wraps a compilation size array -
A standard library class
std::vector<T>
that uses dynamically allocated memory and can resize itself at runtime when data is inserted, copying items from the old to a larger newly allocated memory area as needed
The latter clauses of the library are usually preferred to use T[constant]
or new T[variable]
because they add object-oriented functions such as member functions for .size()
, iterators, and for vector
a destructor that performs automatic element destruction and memory removal.
If your tree will have a constant compile-time upper bound on size, you can use std::array
but std::vector
allow dynamic size, which is a more flexible and reliable solution.
More generally, your question may surprise or confuse C ++ programmers, as our common practice is to store binary trees with nodes linked by pointers rather than contiguous storage. What you are asking for is still considered a binary tree in Computing Science - see for example here - but most of us usually use the standard library std::set<>
to do this, which happens using nodes linked by pointers.
source to share