std::map, pointer to map key value, is this possible?(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,指向映射键值的指针,这可能吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:std::map,指向映射键值的指针,这可能吗?
基础教程推荐
- 如果我为无符号变量分配负值会发生什么? 2022-01-01
- CString 到 char* 2021-01-01
- 初始化列表*参数*评估顺序 2021-01-01
- 为什么派生模板类不能访问基模板类的标识符? 2021-01-01
- GDB 显示调用堆栈上函数地址的当前编译二进制文 2022-09-05
- 为什么 RegOpenKeyEx() 在 Vista 64 位上返回错误代码 2021-01-01
- 我应该对 C++ 中的成员变量和函数参数使用相同的名称吗? 2021-01-01
- 通过引用传递 C++ 迭代器有什么问题? 2022-01-01
- 为什么 typeid.name() 使用 GCC 返回奇怪的字符以及如 2022-09-16
- 非静态 const 成员,不能使用默认赋值运算符 2022-10-09
