一、vector 中的数据删除
- vector 中删除元素,使用 erase 来达到目的
int main() {
vector<int> vecInts;
vecInts.push_back(1);
vecInts.push_back(2);
vecInts.push_back(3);
vecInts.push_back(3);
vecInts.push_back(4);
// 删除一个中间的非相同元素,这种方法可以达到目的
// for (auto it = vecInts.begin(); it != vecInts.end(); it++) {
// if (*it == 2) {
// vecInts.erase(it);
// }
// }
// 删除相邻相同的元素
// for (auto it = vecInts.begin(); it != vecInts.end(); it++) {
// if (*it == 3) {
// vecInts.erase(it); //出现 core, 由于迭代器改变
// }
// }
// 删除元素在最后
// for (auto it = vecInts.begin(); it != vecInts.end(); it++) {
// if (*it == 4) {
// vecInts.erase(it); //出现 core, 由于对 end() 进行++操作
// }
// }
// 通用的正确使用 erase 方法
for (auto it = vecInts.begin(); it != vecInts.end(); ) {
if (*it == 3) {
it = vecInts.erase(it); //出现 core, 由于对 end() 进行++操作
} else {
it++;
}
}
}
二、map 中的元素删除
- 同 vector 中的删除方法