Can i use vector as base data store for binary tree

I am creating a binary tree to search for data. All of the examples I've come across use an array as their primary storage engine. However, my data is stored in a vector. Can a vector be used as the underlying storage engine for a binary tree?

+3


source to share


3 answers


The answer is yes, you can - and that's desirable from a performance standpoint. The implementation was specially written for you in the boost library.



http://www.boost.org/doc/libs/1_58_0/doc/html/container/non_standard_containers.html#container.non_standard_containers.flat_xxx

+7


source


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.

+1


source


Yes.

You use arrays if you want to perform calculations faster. However, the size of your binary tree (or depth, or any order) cannot be changed if you are using arrays.

0


source







All Articles