- std:: vector::erase
- Parameters
- Return value
- Example
- Complexity
- Iterator validity
- Data races
- Exception safety
- See also
- std::vector:: erase
- Contents
- [edit] Parameters
- [edit] Return value
- [edit] Exceptions
- [edit] Complexity
- [edit] Notes
- [edit] Example
- [edit] Defect reports
- std:: vector
- Contents
- [edit] Template parameters
- [edit] Specializations
- [edit] Iterator invalidation
std:: vector::erase
Removes from the vector either a single element (position) or a range of elements ([first,last)).
This effectively reduces the container size by the number of elements removed, which are destroyed.
Because vectors use an array as their underlying storage, erasing elements in positions other than the vector end causes the container to relocate all the elements after the segment erased to their new positions. This is generally an inefficient operation compared to the one performed for the same operation by other kinds of sequence containers (such as list or forward_list).
Parameters
position Iterator pointing to a single element to be removed from the vector.
Member types iterator and const_iterator are random access iterator types that point to elements. first, last Iterators specifying a range within the vector] to be removed: [first,last). i.e., the range includes all the elements between first and last, including the element pointed by first but not the one pointed by last.
Member types iterator and const_iterator are random access iterator types that point to elements.
Return value
An iterator pointing to the new location of the element that followed the last element erased by the function call. This is the container end if the operation erased the last element in the sequence.
Member type iterator is a random access iterator type that points to elements.
Example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
// erasing from vector int main () < std::vectorint> myvector; // set some values (from 1 to 10) for (int i=1; i// erase the 6th element myvector.erase (myvector.begin()+5); // erase the first 3 elements: myvector.erase (myvector.begin(),myvector.begin()+3); std::cout "myvector contains:"; for (unsigned i=0; i << myvector[i]; std::cout '\n'; return 0; >
myvector contains: 4 5 7 8 9 10
Complexity
Linear on the number of elements erased (destructions) plus the number of elements after the last element deleted (moving).
Iterator validity
Iterators, pointers and references pointing to position (or first) and beyond are invalidated, with all iterators, pointers and references to elements before position (or first) are guaranteed to keep referring to the same elements they were referring to before the call.
Data races
The container is modified.
None of the elements before position (or first) is accessed, and concurrently accessing or modifying them is safe.
Exception safety
If the removed elements include the last element in the container, no exceptions are thrown (no-throw guarantee).
Otherwise, the container is guaranteed to end in a valid state (basic guarantee).
An invalid position or range causes undefined behavior.
See also
vector::pop_back Delete last element (public member function) vector::insert Insert elements (public member function)
std::vector:: erase
Invalidates iterators and references at or after the point of the erase, including the end() iterator.
The iterator pos must be valid and dereferenceable. Thus the end() iterator (which is valid, but is not dereferenceable) cannot be used as a value for pos .
The iterator first does not need to be dereferenceable if first == last : erasing an empty range is a no-op.
Contents
[edit] Parameters
pos | — | iterator to the element to remove |
first, last | — | range of elements to remove |
Type requirements | ||
— |
[edit] Return value
Iterator following the last removed element.
[edit] Exceptions
Does not throw unless an exception is thrown by the assignment operator of T .
[edit] Complexity
Linear: the number of calls to the destructor of T is the same as the number of elements erased, the assignment operator of T is called the number of times equal to the number of elements in the vector after the erased elements
[edit] Notes
When container elements need to be erased based on a predicate, rather than iterating the container and calling unary erase , the iterator range overload is generally used with std::remove()/std::remove_if() to minimise the number of moves of the remaining (non-removed) elements, this is the erase-remove idiom. std::erase_if() replaces the erase-remove idiom. (since C++20)
[edit] Example
#include #include void print_container(const std::vectorint>& c) { for (int i : c) std::cout <" "; std::cout <'\n'; } int main( ) { std::vectorint> c{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}; print_container(c); c.erase(c.begin()); print_container(c); c.erase(c.begin() + 2, c.begin() + 5); print_container(c); // Erase all even numbers for (std::vectorint>::iterator it = c.begin(); it != c.end();) { if (*it % 2 == 0) it = c.erase(it); else ++it; } print_container(c); }
0 1 2 3 4 5 6 7 8 9 1 2 3 4 5 6 7 8 9 1 2 6 7 8 9 1 7 9
[edit] Defect reports
The following behavior-changing defect reports were applied retroactively to previously published C++ standards.
DR | Applied to | Behavior as published | Correct behavior |
---|---|---|---|
LWG 151 | C++98 | first was required to be dereferenceable, which made the behavior of clearing an empty vector undefined | not required if first == last |
LWG 414 | C++98 | iterators at the point of erase were not invalidated | they are also invalidated |
std:: vector
The elements are stored contiguously, which means that elements can be accessed not only through iterators, but also using offsets to regular pointers to elements. This means that a pointer to an element of a vector may be passed to any function that expects a pointer to an element of an array.
The storage of the vector is handled automatically, being expanded as needed. Vectors usually occupy more space than static arrays, because more memory is allocated to handle future growth. This way a vector does not need to reallocate each time an element is inserted, but only when the additional memory is exhausted. The total amount of allocated memory can be queried using capacity() function. Extra memory can be returned to the system via a call to shrink_to_fit() . (since C++11)
Reallocations are usually costly operations in terms of performance. The reserve() function can be used to eliminate reallocations if the number of elements is known beforehand.
The complexity (efficiency) of common operations on vectors is as follows:
- Random access — constant O(1)
- Insertion or removal of elements at the end — amortized constant O(1)
- Insertion or removal of elements — linear in the distance to the end of the vector O(n)
std::vector (for T other than bool ) meets the requirements of Container , AllocatorAwareContainer (since C++11) , SequenceContainer , ContiguousContainer (since C++17) and ReversibleContainer .
Member functions of std::vector are constexpr : it is possible to create and use std::vector objects in the evaluation of a constant expression.
However, std::vector objects generally cannot be constexpr , because any dynamically allocated storage must be released in the same evaluation of constant expression.
Contents
[edit] Template parameters
The requirements that are imposed on the elements depend on the actual operations performed on the container. Generally, it is required that element type meets the requirements of Erasable , but many member functions impose stricter requirements. This container (but not its members) can be instantiated with an incomplete element type if the allocator satisfies the allocator completeness requirements.
[edit] Specializations
The standard library provides a specialization of std::vector for the type bool , which may be optimized for space efficiency.
[edit] Iterator invalidation
Operations | Invalidated |
---|---|
All read only operations | Never |
swap , std::swap | end() |
clear , assign | Always |
reserve , shrink_to_fit | If the vector changed capacity, all of them. If not, none. |
erase | Erased elements and all elements after them (including end() ) |
push_back , emplace_back | If the vector changed capacity, all of them. If not, only end() . |
insert , emplace | If the vector changed capacity, all of them. If not, only those at or after the insertion point (including end() ). |
resize | If the vector changed capacity, all of them. If not, only end() and any elements erased. |
pop_back | The element erased and end() . |