std::map, pointer to map key value, is this possible?

后端 未结 4 1409
悲&欢浪女
悲&欢浪女 2020-12-01 06:14
std::map myMap;

std::map::iterator i = m_myMap.find(some_key_string);
if(i == m_imagesMap.end())
            


        
相关标签:
4条回答
  • 2020-12-01 07:04

    First, maps are guaranteed to be stable; i.e. the iterators are not invalidated by element insertion or deletion (except the element being deleted of course).

    However, stability of iterator does not guarantee stability of pointers! Although it usually happens that most implementations use pointers - at least at some level - to implement iterators (which means it is quite safe to assume your solution will work), what you should really store is the iterator itself.

    What you could do is create a small object like:

    struct StringPtrInMap
    {
      typedef std::map<string,string>::iterator iterator;
      StringPtrInMap(iterator i) : it(i) {}
      const string& operator*() const { return it->first; }
      const string* operator->() const { return &it->first; }
      iterator it;
    }
    

    And then store that instead of a string pointer.

    0 讨论(0)
  • 2020-12-01 07:06

    If you're not sure which operations will invalidate your iterators, you can look it up pretty easily in the reference. For instance for vector::insert it says:

    This effectively increases the vector size, which causes an automatic reallocation of the allocated storage space if, and only if, the new vector size surpases the current vector capacity. Reallocations in vector containers invalidate all previously obtained iterators, references and pointers.

    map::insert on the other hand doesn't mention anything of the sort.

    As Pierre said, you should store the iterator rather than the pointer, though.

    0 讨论(0)
  • 2020-12-01 07:06

    Why are you wanting to do this?

    You can't change the value of *p, since it's const std::string. If you did change it, then you might break the invariants of the container by changing the sort order of the elements.

    Unless you have other requirements that you haven't given here, then you should just take a copy of the string.

    0 讨论(0)
  • 2020-12-01 07:20

    Section 23.1.2#8 (associative container requirements):

    The insert members shall not affect the validity of iterators and references to the container, and the erase members shall invalidate only iterators and references to the erased elements.

    So yes storing pointers to data members of a map element is guaranteed to be valid, unless you remove that element.

    0 讨论(0)
提交回复
热议问题