Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
25 changes: 25 additions & 0 deletions include/core/node.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
#pragma once

#include <string>
#include <vector>
#include <memory>

class Node: public std::enable_shared_from_this<Node>
{
public:
explicit Node(std::shared_ptr<Node> parent = nullptr, std::string name = "without name");

~Node();

std::shared_ptr<Node> get_parent() const;
std::vector<std::shared_ptr<Node>> get_children() const;
std::shared_ptr<Node> add_child();
void remove_child(std::shared_ptr<Node> child);
std::string get_name() const;
void change_name(std::string new_name);

private:
const std::weak_ptr<Node> _parent;
std::vector<std::shared_ptr<Node>> _child;
std::string _name;
};
71 changes: 71 additions & 0 deletions src/core/node.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,71 @@
#include "core/node.h"
#include "core/logging.h"

Node::Node(std::shared_ptr<Node> parent, std::string name)
: _name(name), _parent(parent)
{
if (parent != nullptr)
{
parent->_child.push_back(shared_from_this());
}
}

Node::~Node()
{
_child.clear();
auto parent = _parent.lock();
if (parent) {
parent->remove_child(shared_from_this());
}
}

std::shared_ptr<Node> Node::get_parent() const
{
return _parent.lock();
}

std::vector<std::shared_ptr<Node>> Node::get_children() const
{
return _child;
}

std::shared_ptr<Node> Node::add_child()
{
Node child(*this);
std::shared_ptr<Node> child_ptr = std::make_shared<Node>(child);
_child.push_back(child_ptr);
return child_ptr;
}

void Node::remove_child(std::shared_ptr<Node> del_child)
{
std::vector<std::shared_ptr<Node>>::iterator child_iter = _child.begin();
auto del_child_iter = _child.end();
while(child_iter != _child.end())
{
if (*child_iter == del_child)
{
del_child_iter = child_iter;
break;
}
child_iter++;
}
if (del_child_iter == _child.end())
{
LOGW("Not possible to delete a non-existent child");
}
else
{
_child.erase(del_child_iter);
}
}

std::string Node::get_name() const
{
return _name;
}

void Node::change_name(std::string new_name)
{
_name = new_name;
}