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

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

问题描述

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将变得无效?

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,指向map key的值,这是可能吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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