对STD集合返回的元素(如地图)的引用有效期多长?
例如,在此代码中:
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?
Run Code Online (Sandbox Code Playgroud)
}
换句话说,我从地图中获取了一个值引用.但后来我在底层地图上进行了各种其他插入,删除等操作.原值参考仍然是好的吗?其他系列呢?
而且,我怎么知道呢?我看着Stroustrup,但没有看到任何东西.
来自C背景我对引用和集合及其交互感到困惑.我应该考虑其值是参考的地图吗?这甚至意味着什么?
这是一个更普遍的问题:我在哪里可以找到这个问题和类似问题的规范性答案?
[这是已删除问题的修订版]
Ton*_*roy 10
std::map 通过使迭代器无效的相同操作使引用无效 - 这在标准和cppreference.com等地方都有详细记录.
综上所述了std::map,因为你没有引用是只要有效clear的map,或erase指定的被引用元素; 插入或删除其他元素很好.例如,cpprefererence map :: insert文档说"没有迭代器或引用无效.".
你会发现有关于其他容器及其操作的陈述....(jrok在注释中指出,push deque是一个操作的例子,其中引用仍然有效,但迭代器无效).
| 归档时间: |
|
| 查看次数: |
469 次 |
| 最近记录: |