|
vector::insertpublic member function
iterator insert ( iterator position, const T& x ); void insert ( iterator position, size_type n, const T& x ); template <class InputIterator> void insert ( iterator position, InputIterator first, InputIterator last ); Insert elements The vector is extended by inserting new elements before the element at position.This effectively increases the vector size, which causes an automatic reallocation of the allocated storage space if, and only if, the new vector size surpasses the current vector capacity. Reallocations in vector containers invalidate all previously obtained iterators, references and pointers. Because vectors keep an array format, insertions on positions other than the vector end are performed by moving all the elements between position and the end of the vector to their new positions, and then inserting the new element(s), which may not be a method as efficient as the insertion in other kinds of sequence containers (deque, list). The parameters determine how many elements are inserted and to which values they are initialized: Parameters
Return valueOnly the first version returns a value, which is an iterator that points to the newly inserted element.If reallocations happen, they are performed using Allocator::allocate(), which may throw exceptions (for the default allocator, bad_alloc is thrown if the allocation request does not succeed). Example
Output:
ComplexityIf the new vector size can be determined beforehand, linear on the number of elements inserted (copy construction) plus the number of elements between position and the end of the vector (moving).If the new vector size cannot be determined beforehand (which happens in the iterator version for input iterators that are neither forward, bidirectional nor random-access), the complexity is proportional to the number of elements inserted times the distance between position and the end of the vector. See also
|