如果 std::vector::insert(pos, value) 的 pos 无效怎么办?
What if std::vector::insert(pos, value) with an invalid pos?
根据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).
如果 pos
无效,文档没有明确描述以下问题:
- return 值是多少?
- 是否会抛出异常?
所以,我的问题是:
如果std::vector::insert(pos, value)
无效怎么办pos
?
std::vector
是一个序列容器。 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
表示 a
" 的有效常量迭代器,其中 a
是向量。
因此位置迭代器必须是 a
的有效迭代器。除非描述了不同的后果,否则默认情况下不遵守功能要求是未定义的行为。
(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.
根据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).
如果 pos
无效,文档没有明确描述以下问题:
- return 值是多少?
- 是否会抛出异常?
所以,我的问题是:
如果std::vector::insert(pos, value)
无效怎么办pos
?
std::vector
是一个序列容器。 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
表示 a
" 的有效常量迭代器,其中 a
是向量。
因此位置迭代器必须是 a
的有效迭代器。除非描述了不同的后果,否则默认情况下不遵守功能要求是未定义的行为。
(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.