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,指向映射键值的指针,这可能吗?
基础教程推荐
- C++,'if' 表达式中的变量声明 2021-01-01
- 调用std::Package_TASK::Get_Future()时可能出现争用情况 2022-12-17
- 如何在 C++ 中处理或避免堆栈溢出 2022-01-01
- 如何定义双括号/双迭代器运算符,类似于向量的向量? 2022-01-01
- C++ 程序在执行 std::string 分配时总是崩溃 2022-01-01
- 什么是T&&(双与号)在 C++11 中是什么意思? 2022-11-04
- C++ 标准:取消引用 NULL 指针以获取引用? 2021-01-01
- 运算符重载的基本规则和习语是什么? 2022-10-31
- 您如何将 CreateThread 用于属于类成员的函数? 2021-01-01
- 设计字符串本地化的最佳方法 2022-01-01