首页 > 解决方案 > “继承”另一个(1:N)关系的关系

问题描述

我想要一个支持这些特定 1:N 关系的数据结构:-
1#。Human 提高0-N Human
2#。Human 0-N Dog
3#。Human 培养0-N Tree
4#。Dog 0-N的房子Parasites

在此处输入图像描述

注意:
- 这些关系中的状态都是暂时的,例如Human1可以提高 Human2,但一年后,Human1可以放弃Human2
- 所有对象都继承自BaseObject并具有唯一的 int ID。

在上述所有关系中,我希望能够支持这些功能:-
F1。添加关系,例如human_dog->addRelation(Human* a,Dog* b)
F2。删除关系,例如human_dog->removeRelation(Human* a,Dog* b)
F3。查询所有孩子,例如human_dog->getAllChildren(Human*)
F4。查询所有父级,例如human_dog->getAllParents(Dog*)
F5。检查父母是否有 >=1 孩子
F6. 检查一个孩子是否有> = 1个父母
F7。删除父
级 F8 的所有子级。删除孩子的所有父母

这可以std::unordered_map很容易地由更容易定制的东西来实现。

困难的部分来了

我想将关系 1#,2#,3# (即所有实线)标记为Feed
它必须以聚合方式支持功能 F3-F8。

例如 :-

总之,我希望能够轻松地注入这样的聚合
前任。打电话很有用:-

void BaseObject::declareForFreedom(){
    feed->removeAllParent(this);
}

上面的示例仅显示了 4 个关系和 1 个间接级别。
在我的真实案例中,有 8-10 个关系和 3-4 个级别的继承/间接。

问题

适合这种情况的数据结构/设计模式是什么?

我目前为 1#-4# 创建一个自定义的 1:N 关系,并对每个feed的函数进行硬编码。这很乏味。
我已经用头撞了几个月,但没有找到任何看起来优雅的实现。

演示

http://coliru.stacked-crooked.com/a/1f2decd7a8d96e3c

基本类型:-

#include <iostream>
#include <map>
#include <vector>
enum class Type{
    HUMAN,DOG,TREE,PARASITE,ERROR
}; //for simplicity
class BaseObject{public: Type type=Type::ERROR; };
class Human : public BaseObject{
    public: Human(){ type=Type::HUMAN; }    
};
class Dog : public BaseObject{
    public: Dog(){ type=Type::DOG; }    
};
class Tree : public BaseObject{
    public: Tree(){ type=Type::TREE; }    
};
class Parasite : public BaseObject{
    public: Parasite(){ type=Type::PARASITE; }    
};

基本 1:N 地图

template<class A,class B> class MapSimple{
    std::multimap<A*, B*> aToB;
    std::multimap<B*, A*> bToA;
    public: void addRelation(A* b1,B* b2){
        aToB.insert ( std::pair<A*,B*>(b1,b2) );   
        bToA.insert ( std::pair<B*,A*>(b2,b1) );   
    }
    public: std::vector<B*> queryAllChildren(A* b1){
        auto ret = aToB.equal_range(b1);
        auto result=std::vector<B*>();
        for (auto it=ret.first; it!=ret.second; ++it){
            result.push_back(it->second);
        }
        return result;
    }
    public: void removeAllParent(B* b){
        if(bToA.count(b)==0)return;
        A* a=bToA.find(b)->second;
        bToA.erase(b);
        auto iterpair = aToB.equal_range(a);
        auto it = iterpair.first;
        for (; it != iterpair.second; ++it) {
            if (it->second == b) { 
                aToB.erase(it);
                break;
            }
        }
    }
    //.. other functions 
};

这是数据库实例和聚合:-

MapSimple<Human,Human> raise;
MapSimple<Human,Dog> has;
MapSimple<Human,Tree> cultivate;
MapSimple<Dog,Parasite> isHouseOf;
class Feed{
    public: void removeAllParent(BaseObject* b1){
        if(b1->type==Type::HUMAN){
            raise.removeAllParent(static_cast<Human*>(b1));
        } 
        if(b1->type==Type::DOG){
            has.removeAllParent(static_cast<Dog*>(b1));
        }
        //.... some other condition (I have to hard code them - tedious) ...
    }
    //other function 
};
Feed feed;

用法

int main(){
    Human h1;
    Dog d1,d2;

    has.addRelation(&h1,&d1);
    has.addRelation(&h1,&d2);
    auto result=has.queryAllChildren(&h1);
    std::cout<<result.size(); //print 2
    feed.removeAllParent(&d1);
    result=has.queryAllChildren(&h1);
    std::cout<<result.size(); //print 1
}

标签: c++design-patternsdata-structuresgame-engineone-to-many

解决方案


编辑

Jarod42 在本主题中建议了更好的代码。C++17 风格:

#include <algorithm>
#include <tuple>
#include <vector>

class BaseObject {
public:
    virtual ~BaseObject() = default;
    virtual std::vector<BaseObject*> getAllParents() const = 0;
    virtual std::vector<BaseObject*> getAllChildren() const = 0;
    virtual void removeAllParents() = 0;
    virtual void removeAllChildren() = 0;
};

template<typename TParentTuple, typename TChilderenTuple>
class Obj;

template<typename... ParentTags,
         typename... ChildTags>
class Obj<std::tuple<ParentTags...>, std::tuple<ChildTags...>> : public BaseObject
{
    std::tuple<std::vector<typename ParentTags::obj_type*>...> parents;
    std::tuple<std::vector<typename ChildTags::obj_type*>...> children;

public:

    template <typename T>
    void addParent(T* parent) { std::get<std::vector<T*>>(parents).push_back(parent); }

    template <typename T>
    void removeParent(const T* parent) {
        auto& v = std::get<std::vector<T*>>(parents);
        auto it = std::find(std::cbegin(v), std::cend(v), parent);
        if (it != std::cend(v)) { v.erase(it); }
    }

    template <typename T>
    void addChild(T* child) { std::get<std::vector<T*>>(children).push_back(child); }

    template <typename T>
    void removeChild(const T* child) {
        auto& v = std::get<std::vector<T*>>(children);
        auto it = std::find(std::cbegin(v), std::cend(v), child);
        if (it != std::cend(v)) { v.erase(it); }
    }

    std::vector<BaseObject*> getAllParents() const override {
        std::vector<BaseObject*> res;

        std::apply([&](auto&... v){ (res.insert(res.end(), v.begin(), v.end()), ...); },
                   parents);
        return res;
    }
    std::vector<BaseObject*> getAllChildren() const override {
        std::vector<BaseObject*> res;

        std::apply([&](auto&... v){ (res.insert(res.end(), v.begin(), v.end()), ...); },
                   children);
        return res;
    }

    void removeAllParents() override {
        std::apply(
            [this](auto&... v)
            {
                [[maybe_unused]] auto clean = [this](auto& v) {
                    for (auto* parent : v) {
                        parent->removeChild(this);
                    }
                    v.clear();
                };
                (clean(v), ...);
            },
            parents);
    }

    void removeAllChildren() override {
        std::apply(
            [this](auto&... v)
            {
                [[maybe_unused]] auto clean = [this](auto& v) {
                    for (auto* child : v) {
                        child->removeParent(this);
                    }
                    v.clear();
                };
                ( clean(v), ...);
            },
            children);
    }
};

struct Human_tag;
struct Tree_tag;
struct Dog_tag;
struct Parasite_tag;

using Human = Obj<std::tuple<>, std::tuple<Tree_tag, Dog_tag>>;
using Tree = Obj<std::tuple<Human_tag>, std::tuple<>>;
using Dog = Obj<std::tuple<Human_tag>, std::tuple<Parasite_tag>>;
using Parasite = Obj<std::tuple<Dog_tag>, std::tuple<>>;

struct Human_tag { using obj_type = Human; };
struct Tree_tag { using obj_type = Tree; };
struct Dog_tag { using obj_type = Dog; };
struct Parasite_tag { using obj_type = Parasite; };

template<class A, class B>
void addRelation(A* a, B* b)
{
    a->addChild(b);
    b->addParent(a);
}

#include <iostream>
int main() {
    Human h1;
    Dog d1, d2;

    addRelation(&h1, &d1);
    addRelation(&h1, &d2);
    auto result = h1.getAllChildren();
    std::cout << result.size() << "\n"; //print 2
    d1.removeAllParents();
    result = h1.getAllChildren();
    std::cout << result.size() << "\n"; //print 1
}

旧代码:(我的尝试)

好的,因为你不想要重复的代码,所以我一直在使用这个项目作为我第一次体验元编程/可变参数模板。所以这就是我得到的:

#include <tuple>
#include <vector>
#include <algorithm>

template<class T>
using prtVector = std::vector<T*>;

// Interface, as required by assignment
class BaseObject {
public:
    virtual ~BaseObject() {}
    virtual prtVector<BaseObject> getAllParents() const = 0;
    virtual prtVector<BaseObject> getAllChildren() const = 0;
    virtual void removeAllParents() = 0;
    virtual void removeAllChildren() = 0;
};

// base prototype
template<typename TOwnTag, typename TParentTagsTuple, typename TChildTagsTuple>
class Obj;

// Parent-type deduction
template<typename TOwnTag, typename TParentTag, typename... TParentTags, typename... TChildTags>
class Obj<TOwnTag, std::tuple<TParentTag, TParentTags...>, std::tuple<TChildTags...>>
    : public Obj<TOwnTag, std::tuple<TParentTags...>, std::tuple<TChildTags...>>
{
    // local types
    using TOwn = typename TOwnTag::obj_type;
    using TParent = typename TParentTag::obj_type;
    // container
    prtVector<TParent> parentsPtrs;
    //befriend types
    friend class Obj;
    template<class A, class B>
    friend void addRelation(A* const a, B* const b);
protected:
    // prevent base function hiding with 'using'-declaration
    using Obj<TOwnTag, std::tuple<TParentTags...>, std::tuple<TChildTags...>>::addParent;
    using Obj<TOwnTag, std::tuple<TParentTags...>, std::tuple<TChildTags...>>::removeParent;
    // add and remove element functions
    void addParent(TParent* const parentPtr) { parentsPtrs.push_back(parentPtr); }
    void removeParent(TParent const* const parentPtr) {
        auto it = std::find(std::cbegin(parentsPtrs), std::cend(parentsPtrs), parentPtr);
        if (it != std::cend(parentsPtrs)) parentsPtrs.erase(it);
    }
public:
    virtual ~Obj() {}
    virtual prtVector<BaseObject> getAllParents() const override {
        auto result = Obj<TOwnTag, std::tuple<TParentTags...>, std::tuple<TChildTags...>>::getAllParents();
        result.insert(std::begin(result), std::cbegin(parentsPtrs), std::cend(parentsPtrs));
        return result;
    }
    virtual prtVector<BaseObject> getAllChildren() const override {
        return Obj<TOwnTag, std::tuple<TParentTags...>, std::tuple<TChildTags...>>::getAllChildren();
    }
    virtual void removeAllParents() override {
        Obj<TOwnTag, std::tuple<TParentTags...>, std::tuple<TChildTags...>>::removeAllParents();
        for (auto&& parent : parentsPtrs) parent->removeChild(reinterpret_cast<TOwn* const>(this));
    }
    virtual void removeAllChildren() override {
        Obj<TOwnTag, std::tuple<TParentTags...>, std::tuple<TChildTags...>>::removeAllChildren();
    }
};

// Child-type deduction
template<typename TOwnTag, typename TChildTag, typename... TChildTags>
class Obj<TOwnTag, std::tuple<>, std::tuple<TChildTag, TChildTags...>>
    : public Obj<TOwnTag, std::tuple<>, std::tuple<TChildTags...>>
{
    // local types
    using TOwn = typename TOwnTag::obj_type;
    using TChild = typename TChildTag::obj_type;
    // container
    prtVector<TChild> childrenPtrs;
    //befriend types
    friend class Obj;
    template<class A, class B>
    friend void addRelation(A* const a, B* const b);
protected:
    // empty functions required for 'using'-declaration
    void addParent() {}
    void removeParent() {}
    // prevent base function hiding with 'using'-declaration
    using Obj<TOwnTag, std::tuple<>, std::tuple<TChildTags...>>::addChild;
    using Obj<TOwnTag, std::tuple<>, std::tuple<TChildTags...>>::removeChild;
    // add and remove element functions
    void addChild(TChild* const childPtr) { childrenPtrs.push_back(childPtr); }
    void removeChild(TChild const* const childPtr) {
        auto it = std::find(std::cbegin(childrenPtrs), std::cend(childrenPtrs), childPtr);
        if (it != std::cend(childrenPtrs)) childrenPtrs.erase(it);
    }
public:
    virtual ~Obj() {}
    virtual prtVector<BaseObject> getAllParents() const override {
        return Obj<TOwnTag, std::tuple<>, std::tuple<TChildTags...>>::getAllParents();
    }
    virtual prtVector<BaseObject> getAllChildren() const override {
        auto result = Obj<TOwnTag, std::tuple<>, std::tuple<TChildTags...>>::getAllChildren();
        result.insert(std::begin(result), std::cbegin(childrenPtrs), std::cend(childrenPtrs));
        return result;
    }
    virtual void removeAllParents() override {}
    virtual void removeAllChildren() override {
        Obj<TOwnTag, std::tuple<>, std::tuple<TChildTags...>>::removeAllChildren();
        for (auto&& child : childrenPtrs) child->removeParent(reinterpret_cast<TOwn* const>(this));
    }
};

// terminator
template<typename TOwnTag>
class Obj<TOwnTag, std::tuple<>, std::tuple<>> : public BaseObject {
protected:
    // empty functions required for 'using'-declaration
    void addChild() {}
    void removeChild() {}
    void addParent() {}
    void removeParent() {}
public:
    virtual ~Obj() {}
    virtual prtVector<BaseObject> getAllParents() const override {
        return prtVector<BaseObject>();
    }
    virtual prtVector<BaseObject> getAllChildren() const override {
        return prtVector<BaseObject>();
    }
    virtual void removeAllParents() override {}
    virtual void removeAllChildren() override {}
};

//prototype class tags
struct Human_tag;
struct Tree_tag;
struct Dog_tag;
struct Parasite_tag;
//define class types
using Human = Obj<Human_tag, std::tuple<>, std::tuple<Tree_tag, Dog_tag>>;
using Tree = Obj<Tree_tag, std::tuple<Human_tag>, std::tuple<>>;
using Dog = Obj<Dog_tag, std::tuple<Human_tag>, std::tuple<Parasite_tag>>;
using Parasite = Obj<Parasite_tag, std::tuple<Dog_tag>, std::tuple<>>;
//couple tags to classes
struct Human_tag { using obj_type = Human; };
struct Tree_tag { using obj_type = Tree; };
struct Dog_tag { using obj_type = Dog; };
struct Parasite_tag { using obj_type = Parasite; };

//(befriend)helper function
// maybe could do somehting with std::enable_if
// i.e. "enable if type B is in child tuple of A and
//  type A is in parent tuple of B"
// that way the parser will already detect a relation is not possible
template<class A, class B>
void addRelation(A* const a, B* const b)
{
    a->addChild(b);
    b->addParent(a);
}

// now for some testing
#include <iostream>
int main() {
    Human h1;
    Dog d1, d2;
    Parasite p1;

    addRelation(&h1, &d1);
    addRelation(&h1, &d2);
    addRelation(&d1, &p1);
    //addRelation(&h1, &p1); // compiler error
    auto result = h1.getAllChildren();
    std::cout << result.size() << "\n"; //print 2
    d1.removeAllParents();
    result = h1.getAllChildren();
    std::cout << result.size() << "\n"; //print 1

    std::cin.ignore();
}

请就任何不清楚的问题提出问题,因为在过去的 24 小时内我学到了很多新东西,以至于我不知道从哪里开始解释。


推荐阅读