How to define a recursive type?

前端 未结 5 883
孤独总比滥情好
孤独总比滥情好 2021-01-01 14:45

I want to have a list. An entry in the list would store a value as well as an iterator to another entry in the list. How do I define this type? It\'d be something like this,

5条回答
  •  醉梦人生
    2021-01-01 15:31

    You can achieve that by forward declaring your element.

    #include 
    
    struct Element;
    typedef std::list ElementList;
    
    struct Element
    {
        int value;
        ElementList::iterator element;
    };
    
    int main() {
        ElementList l;
        l.push_back({0, l.end()});
        l.push_back({1, l.begin()});
    }
    

提交回复
热议问题