Using std::deque::iterator (in C++ STL) for searching and deleting certain elements

限于喜欢 提交于 2019-12-03 16:56:21
syam

http://en.cppreference.com/w/cpp/container/deque/erase

All iterators and references are invalidated [...]

Return value : iterator following the last removed element.

This is a common pattern when removing elements from an STL container inside a loop:

for (auto i = c.begin(); i != c.end() ; /*NOTE: no incrementation of the iterator here*/) {
  if (condition)
    i = c.erase(i); // erase returns the next iterator
  else
    ++i; // otherwise increment it by yourself
}

Or as chris mentioned you could just use std::remove_if.

To use the erase-remove idiom, you'd do something like:

deq.erase(std::remove_if(deq.begin(),
                         deq.end(),
                         [](int i) { return i%2 == 0; }),
          deq.end());

Be sure to #include <algorithm> to make std::remove_if available.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!