vector
错误做法
这样做会在遍历过程中越界导致程序崩溃
std::vector<int> vecInt({ 1, 3, 2, 1, 4, 1 });for (auto i = vecInt.begin(); i != vecInt.end() ; ++i) {if (*i == 1) {vecInt.erase(i);}}
正确做法
std::vector<int> vecInt({ 1, 3, 2, 1, 4, 1 });for (auto i = vecInt.begin(); i != vecInt.end();) {if (*i == 1) {vecInt.erase(i);}else {++i;}}
调用erase函数后迭代器会指向被删除元素的下一个元素,如果被删除的元素是容器最后一个元素,则指向容器的end()
map
错误做法
std::map<int, std::string> map_i_s;map_i_s.insert({ 1, "1" });map_i_s.insert({ 2, "2" });map_i_s.insert({ 3, "3" });for (auto i = map_i_s.begin(); i != map_i_s.end(); ++i;) {if (i->first > 2) {map_i_s.erase(i);}}
正确做法
std::map<int, std::string> map_i_s;map_i_s.insert({ 1, "1" });map_i_s.insert({ 2, "2" });map_i_s.insert({ 3, "3" });for (auto i = map_i_s.begin(); i != map_i_s.end(); ) {if (i->first > 2) {i = map_i_s.erase(i);}else {++i;}}