問題描述
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,指向映射鍵值的指針,這可能嗎?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!