Just as there are several ways to add elements to a (nonarray
) container there are also several ways to remove elements. These members are listed in Table 9.7.
The members that remove elements do not check their argument(s). The programmer must ensure that element(s) exist before removing them.
pop_front
and pop_back
MembersThe pop_front
and pop_back
functions remove the first and last elements, respectively. Just as there is no push_front
for vector
and string
, there is also no pop_front
for those types. Similarly, forward_list
does not have pop_back
. Like the element access members, we may not use a pop operation on an empty container.
These operations return void
. If you need the value you are about to pop, you must store that value before doing the pop:
while (!ilist.empty()) {
process(ilist.front()); // do something with the current top of ilist
ilist.pop_front(); // done; remove the first element
}
The erase
members remove element(s) at a specified point in the container. We can delete a single element denoted by an iterator or a range of elements marked by a pair of iterators. Both forms of erase
return an iterator referring to the location after the (last) element that was removed. That is, if j
is the element following i
, then erase(i)
will return an iterator referring to j
.
As an example, the following loop erases the odd elements in a list
:
list<int> lst = {0,1,2,3,4,5,6,7,8,9};
auto it = lst.begin();
while (it != lst.end())
if (*it % 2) // if the element is odd
it = lst.erase(it); // erase this element
else
++it;
On each iteration, we check whether the current element is odd. If so, we erase
that element, setting it
to denote the element after the one we erased. If *it
is even, we increment it
so we’ll look at the next element on the next iteration.
The iterator-pair version of erase
lets us delete a range of elements:
// delete the range of elements between two iterators
// returns an iterator to the element just after the last removed element
elem1 = slist.erase(elem1, elem2); // after the call elem1 == elem2
The iterator elem1
refers to the first element we want to erase, and elem2
refers to one past the last element we want to remove.
To delete all the elements in a container, we can either call clear
or pass the iterators from begin
and end
to erase
:
slist.clear(); // delete all the elements within the container
slist.erase(slist.begin(), slist.end()); // equivalent
Exercise 9.25: In the program on page 349 that erased a range of elements, what happens if elem1
and elem2
are equal? What if elem2
or both elem1
and elem2
are the off-the-end iterator?
Exercise 9.26: Using the following definition of ia
, copy ia
into a vector
and into a list
. Use the single-iterator form of erase
to remove the elements with odd values from your list
and the even values from your vector
.
int ia[] = { 0, 1, 1, 2, 3, 5, 8, 13, 21, 55, 89 };