std::map,指向映射键值的指针,这可能吗? [英] std::map, pointer to map key value, is this possible?

查看:34
本文介绍了std::map,指向映射键值的指针,这可能吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

std::map<std::string, std::string> myMap;

std::map<std::string, std::string>::iterator i = m_myMap.find(some_key_string);
if(i == m_imagesMap.end())
    return NULL;

string *p = &i->first;

最后一行有效吗?我想将此指针 p 存储在其他地方,它对整个程序生命周期都有效吗?但是如果我向这个映射添加更多元素(使用其他唯一键)或删除一些其他键会发生什么,它会不会重新分配这个字符串(键值对),所以 p 将变得无效?

Is the last line valid? I want to store this pointer p somewhere else, will it be valid for the whole program life? But what will happen if I add some more elements to this map (with other unique keys) or remove some other keys, won’t it reallocate this string (key-value pair), so the p will become invalid?

推荐答案

首先保证地图稳定;即迭代器不会因元素插入或删除而失效(当然被删除的元素除外).

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.

这篇关于std::map,指向映射键值的指针,这可能吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆