Home > Back-end >  What if std::vector::insert(pos, value) with an invalid pos?
What if std::vector::insert(pos, value) with an invalid pos?

Time:09-18

According to cppref:

constexpr iterator insert( const_iterator pos, const T& value );

Return value

Iterator pointing to the inserted value.

Complexity

Constant plus linear in the distance between pos and end of the container.

Exceptions

If an exception is thrown when inserting a single element at the end, and T is CopyInsertable or std::is_nothrow_move_constructible::value is true, there are no effects (strong exception guarantee).

If pos is invalid, the documentation doesn't clearly describe the following issues:

  1. What's the return value?
  2. Whether an exception will be thrown?

So, my question is:

What if std::vector::insert(pos, value) with an invalid pos?

CodePudding user response:

std::vector is a sequence container. Table 77: Sequence container requirements listes the first argument of every insert overload as being p which is defined just before the table as : "p denotes a valid constant iterator to a" where a is the vector.

So the position iterator is required to be a valid iterator to a. Unless a different consequence is described, failing to respect a requirement of a feature is by default Undefined Behavior.

CodePudding user response:

Iteator requirements, 15

(15) An invalid iterator is an iterator that may be singular (223)

(223) This definition applies to pointers, since pointers are iterators. The effect of dereferencing an iterator that has been invalidated is undefined.

  • Related