How to define a recursive type?

前端 未结 5 998
孤独总比滥情好
孤独总比滥情好 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:38

    Not only will iterators in a list not be invalidated by other elements being inserted or deleted, but the elements those iterators point to will also remain unchanged. Therefore we can do:

    struct Element {
      int first;
      Element* second;
    };
    
    typedef list MyList;
    

    This is quite similar to what you asked for, but second is a pointer rather than an iterator. If you really need it to be an iterator, we can switch out std::list<> for boost::intrusive::list<> (or a homegrown intrusive list if you can't use Boost). Then, the value_type (i.e. Element) would actually contain the prev/next pointers, and you could use that as an iterator. In Boost, that's called iterator_to(), explained here: http://www.boost.org/doc/libs/1_43_0/doc/html/intrusive/obtaining_iterators_from_values.html

提交回复
热议问题