[C++]迭代器失效

迭代器失效

先看一段代码

#include 
#include 
#include 




int main() {
  int cnt = 0;
  std::set s{1,4};
  std::vector vec{0,1,2,3,4,5,6,7,8,9};
  for (auto iter = vec.begin(); iter != vec.end();) {
    std::cout << "iter: " << *iter << std::endl;
    if (s.count(*iter)) {
      vec.erase(iter++);
      std::cout << "now: " << *iter << std::endl;
    } else {
      ++iter;
    }
  }

  for (auto &it : vec) {
    std::cout << it << std::endl;
  }
}

你可能感兴趣的:([C++]迭代器失效)