Using Both Map and List for Same Objects

后端 未结 2 1536
抹茶落季
抹茶落季 2021-01-23 13:53

I\'m trying to use both a list and an unordered_map to store the same set of objects. I\'m new to C++, so still getting comfortable with iterators.

Say I have the follow

2条回答
  •  面向向阳花
    2021-01-23 14:24

    If what you want to do is this:

    Is it possible to look up an object by key, and then generate a list iterator from the reference of the object (or from the unordered_map generator?)

    Then you can take advantage of the fact that list iterators aren't invalidated on insertion or erase (unless you erase that particular iterator) and reorganize your structures like this:

    std::list list;
    std::unordered_map::iterator> map;
    
    map.insert(std::make_pair(101, 
        list.insert(list.end(), t1)));
    map.insert(std::make_pair(102, 
        list.insert(list.end(), t2)));
    map.insert(std::make_pair(103, 
        list.insert(list.end(), t3)));
    

    That way your map lookup gives you exactly what you want: a list iterator.

提交回复
热议问题