C++ map — Self referencing iterator

前端 未结 2 1224
萌比男神i
萌比男神i 2021-01-20 01:16

Is there a way to declare a std::map whose value type is an iterator to itself?

map::iterator> myMap;
         


        
2条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-01-20 01:30

    Only through type erasure. For example, you could use std::any

    std::map myMap;
    auto inserted = myMap.emplace("foo", std::any());
    
    // how it can be populated:
    inserted.first->second = inserted.first;
    using it_type = decltype(myMap.begin());
    
    // how values can be extracted:
    auto it = std::any_cast(myMap["foo"]);
    

    EDIT: The following also seems to work (clang-7.0.0 and gcc-8.2), but it is illegal (basically std::map does not specify that incomplete types are allowed):

    struct Iter;
    using Map = std::map;
    struct Iter {
        Map::iterator it;
    };
    

提交回复
热议问题