对STD集合返回的元素(如地图)有多长时间的引用?
How long is a reference to an element returned by an STD collection, such as a map, valid?
例如,在此代码中:
struct Employee{ int salary; string name; // the key }; map<string,Employee> allemployees; ... Employee & Joe = allemployees["Joe Smith"]; Joe.salary=150; // change "Joe Smith"'s salary assert(allemployees["Joe Smith"].salary==150); //always true .... allemployees["Mark Jones"]= Employee(); ... // No "Joe Smith" operations in the dots Joe.salary=200; assert (allemployees["Joe Smith"].salary==200); //true or not?}
换句话说,我从地图获取值引用。但是,然后我做了各种其他插入,删除等等的底层地图。原值参考还好吗?对于其他收藏品呢?
In other words, I get a value reference back from a map. But then I do various other insertions, deletions and so on the underlying map. Is the original value reference still good? What about for other collections?
还有,我怎么知道?我看着Stroustrup,但没有看到任何东西。
And also, how do I know that? I looked in Stroustrup but did not see anything.
来自C背景我被引用和集合以及他们的互动困惑。我应该考虑自己的价值是参考的地图吗?这是甚么意思?
Coming from a C background I am confused by references and collections and their interaction. Should I ever consider maps whose values are references themselves? What would that even mean?
所以一个更一般的问题:我在哪里可以找到这个问题的规范答案和类似的问题?
So a more general question: where do I find normative answers to this question and similar kinds of questions?
[这是已删除问题的修订版本]
[This is the revised version of a deleted question]
推荐答案std :: map 引用通过相同的操作使无效的迭代器无效 - 这在标准和cppreference等地方有很好的记录。
std::map references are invalidated by the same actions that would invalidate an iterator - that's well documented in the Standard and places like cppreference.
概括地说, std :: map ,只要你不清除 映射或擦除具体引用的元素;插入或删除其他元素是很好的。例如, cpprefererence map :: insert documentation 说没有迭代器或参考文献无效。
Summarily for std::map, the references are valid as long as you don't clear the map, or erase the specific referenced element; inserting or erasing other elements is fine. For example, cpprefererence map::insert documentation says "No iterators or references are invalidated.".
你会发现有关于其他容器及其操作的声明.... (jrok在评论中指出,到 deque 是一个操作的示例,其中引用保持有效但迭代器无效)。
You'll find there are statements about other containers and their operations.... (jrok pointed out in comments that push to deque is an example of an operation where references remain valid but iterators are invalidated).
更多推荐
STD系列中的参考文献的生命周期
发布评论