CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 8 of 8

Threaded View

  1. #4
    Join Date
    Feb 2017
    Posts
    674

    Re: creation of simple tree like structure using stl vector c++, need help : )

    Quote Originally Posted by vlnikolic View Post
    i would like to create a tree like structure in c++. since the number of children per node is arbitrary i would like to use stl vector for tree creation.
    You could start from an implementation of a binary tree. There are plenty available on the internet and in textbooks.

    In the node declaration, replace the left and right child node pointers with a std::vector of the same pointer type. Then modify the code to use the 0'th and 1'st vector index positions for the left and right pointers, respectively. When this works, you can easily generalize the code to handle an arbitrary number of child pointers in each node by looping over the vector.

    As the last step, if the pointers are low-level, I suggest you replace them with smart pointers. That is std::unique_ptr or std::shared_ptr. In this way, you need not worry about memory leaks from not having deleted discarded node objects properly.
    Last edited by wolle; September 26th, 2022 at 02:40 AM.

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  





Click Here to Expand Forum to Full Width

Featured