Last active
March 28, 2022 07:27
-
-
Save deadblue/ae5aad49d4e9746459e899d765905a72 to your computer and use it in GitHub Desktop.
C++ TreeNode
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <iostream> | |
#include "tree_node.h" | |
using StringTreeNode = TreeNode<std::string>; | |
int main(int argc, char const *argv[]) { | |
auto root = std::make_shared<StringTreeNode>(""); | |
auto a = root->Attach("a", "123"); | |
a->Attach("x", "foo"); | |
a->Attach("y", "bar"); | |
root->Attach("b", "456"); | |
return 0; | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#ifndef TREE_NODE_H | |
#define TREE_NODE_H | |
#include <map> | |
#include <memory> | |
#include <string> | |
#define TREE_NODE_DEBUG 1 | |
template<typename T> | |
struct TreeNode { | |
// Fields | |
#if defined(TREE_NODE_DEBUG) && TREE_NODE_DEBUG | |
std::string path {""}; | |
#endif | |
T value; | |
std::map<std::string, std::shared_ptr<TreeNode<T>>> children; | |
// Constructor | |
TreeNode(T && value): value(std::move(value)) {} | |
// Disable copy and move | |
TreeNode(const TreeNode &other) = delete; | |
TreeNode(TreeNode && other) = delete; | |
#if defined(TREE_NODE_DEBUG) && TREE_NODE_DEBUG | |
~TreeNode() { | |
printf("Release node: %s\n", path.c_str()); | |
} | |
#endif | |
// Methods: | |
inline std::shared_ptr<TreeNode<T>> Attach( | |
const std::string & key, T && value | |
) { | |
auto child = std::make_shared<TreeNode<T>>(std::move(value)); | |
children[key] = child; | |
#if defined(TREE_NODE_DEBUG) && TREE_NODE_DEBUG | |
child->path.append(path).append("/").append(key); | |
#endif | |
return child; | |
} | |
inline bool Has(const std::string & key) const { | |
return children.count(key) > 0; | |
} | |
inline std::shared_ptr<TreeNode<T>> Get(const std::string & key) { | |
return children[key]; | |
} | |
}; | |
#endif // TREE_NODE_H |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment