1. list/vector 元素的删除
iterator erase (iterator position);
iterator erase (iterator first, iterator last);
删除迭代器所指向的元素,或者范围
erase函数返回指向 被删除元素后一个元素 的迭代器
2. 正确的使用方式
#include<iostream>
#include<vector>
int main() {
std::vector<int> vec;
vec.push_back(1);
vec.push_back(2);
vec.push_back(3);
vec.push_back(3);
std::vector<int>::iterator it;
for (it = vec.begin(); it != vec.end(); ) {
if (*it == 3) {
it = vec.erase(it);
} else {
++it;
}
}
for (it = vec.begin(); it != vec.end(); ++it) {
std::cout << *it << std::endl;
}
}
2. 错误的使用方式
#include<iostream>
#include<vector>
int main() {
std::vector<int> vec;
vec.push_back(1);
vec.push_back(2);
vec.push_back(3);
vec.push_back(3);
std::vector<int>::iterator it;
for (it = vec.begin(); it != vec.end(); it++) {
if (*it == 3) {
vec.erase(it);
}
}
for (it = vec.begin(); it != vec.end(); ++it) {
std::cout << *it << std::endl;
}
}
网友评论