The C++ std::deque::erase() function is used to remove an element specified by the iterator or a range from the deque. It can delete a single element at a given position or a range of elements defined by two iterators. After erasing, it adjusts the size of the deque accordingly.
This function has 2 polymorphic variants: with position version or range version (you can find the syntaxes of all the variants below).
SyntaxFollowing is the syntax for std::deque::erase() function.
iterator erase (const_iterator position ); or iterator erase (const_iterator first, const_iterator last );Parameters
position − Iterator points to the deque element.
Return valueIt returns an iterator pointing to the new location of the element.
ExceptionsIt throws an exception (undefined behaviour), if position is invalid.
Time complexityThe time complexity of this function is Linear i.e. O(n)
ExampleLet's look at the following example, where we are going to use the position version to erase the element.
#include <iostream> #include <deque> int main() { std::deque<char> a = {'A', 'B', 'C', 'D', 'E'}; auto x = a.begin() + 2; a.erase(x); for (char num : a) { std::cout << num << " "; } std::cout << std::endl; return 0; }Output
Output of the above code is as follows −
A B D EExample
Consider the another scenario, where we are going to erase the elements using range version.
#include <iostream> #include <deque> int main() { std::deque<int> a = {1, 22,321,4321,12345}; auto x = a.begin() + 1; auto y = a.begin() + 4; a.erase(x, y); for (auto num : a) { std::cout << num << " "; } std::cout << "\n"; return 0; }Output
Following is the output of the above code −
1 12345
deque.htm
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4