Removing an Element Using a Reverse Iterator
When working with STL containers, erasing an element using a reverse iterator can pose a challenge. By default, the erase function expects an iterator, not a reverse iterator.
To resolve this issue, there are several approaches:
1. Obtaining the Base Iterator:
The standard defines a relationship between a reverse iterator (i) and its corresponding base iterator (i.base()) as &*(reverse_iterator(i)) == &*(i - 1). This means you can obtain the base iterator by applying --() to i.base().
2. C 11-Specific Solutions:
In C 11, you have two additional options:
Example Code:
for (std::list<Cursor::Enum>::reverse_iterator i = m_CursorStack.rbegin(); i != m_CursorStack.rend(); ++i) { if (*i == pCursor) { // C++11 solution m_CursorStack.erase(std::next(i).base()); // Alternatively, for pre-C++11 or if desired: m_CursorStack.erase(--(i.base())); break; } }
By following these approaches, you can effectively erase an element from a list using a reverse iterator while adhering to the standard's requirements.
The above is the detailed content of How to Safely Erase Elements from an STL Container Using a Reverse Iterator?. For more information, please follow other related articles on the PHP Chinese website!