1. 要接收erase返回的迭代器
2. erase返回的迭代器自动指向下一个位置,所以代码里有erase的, 要注意只有不运行erase的部分需要 iterator++
int main() { std::vector<int> myInt; myInt.push_back(1); myInt.push_back(2); myInt.push_back(3); //for (auto iter = myInt.begin(); for (vector<int>::iterator iter = myInt.begin();iter != myInt.end();) //iter++ 不要写在这里 { if (*iter == 1) { cout << "erase" << *iter << endl; iter = myInt.erase(iter); //要接收earse返回的iter //不要iter++ } else { cout << "no erase" << *iter << endl; iter++; //iter++ 写在这里 } } while (1); } int main() { std::vector<int> myInt; myInt.push_back(1); myInt.push_back(2); myInt.push_back(3); vector<int>::iterator iter = myInt.begin(); while (iter != myInt.end()) { if (*iter == 1) { cout << "erase" << *iter << endl; iter = myInt.erase(iter); } else { cout << "no erase" << *iter << endl; ++iter; } } while (1); }
