【发布时间】:2017-04-19 16:43:17
【问题描述】:
我知道擦除将使迭代器在擦除点和之后失效。考虑:
std::vector<int> vec = {1, 2, 3, 4, 5};
std::vector<int>::iterator it = vec.end() - 1; //last element
vec.erase(vec.begin()); //shift everything one to the left, 'it' should be the new 'end()' ?
std::cout << (it == vec.end()); //not dereferencing 'it', just comparing, UB ?
比较(而不是取消引用)无效的迭代器(在这种情况下为it)是未定义的行为吗?如果不是,it == vec.end() 是否保证为真?
编辑:如果只有it 是奇异值,则从最上面的答案看来,这是 UB。但从What is singular and non-singular values in the context of STL iterators? 看来,it 似乎(或曾经)与容器相关联,因此使it 非单数。
感谢您对此进行进一步分析。
【问题讨论】:
标签: c++ vector iterator language-lawyer undefined-behavior