Does std::vector::insert() invalidate iterators if the vector has enough room (created through reserve)?

前端 未结 3 2020
故里飘歌
故里飘歌 2020-12-07 05:15

Answering How to self-copy a vector? has got me a bit confused about iterator invalidation. Some literature says \"if you use insert, push_back, etc. consider all iterators

3条回答
  •  粉色の甜心
    2020-12-07 05:30

    Although it is true that insertions into a vector won't cause reallocation as long as the capacity is not exceeded, and won't invalidate iterators to elements before the insertion point (which is arguably the case of end(), as @KerrekSB pointed out), Table 100 of the C++11 Standard (Paragraph 23.2.3) specifies the following precondition for the a.insert(p,i,j) function for sequence containers:

    [...] pre: i and j are not iterators into a. [...]

    In your case, they clearly are, which makes me think that program has Undefined Behavior.

提交回复
热议问题