std::erase总结
std::erase:
(1)string& erase ( size_t pos = 0, size_t n = npos );
std::string test = "Hello erase!"; test.erase(2, 6); //test.erase(2);
//删除指定字符串 //test.erase(test.find("llo"), 3); std::cout << "test: " << test.c_str() << std::endl;
【输出】
- Hease!
- He
- He erase!
(2)iterator erase ( iterator position );
std::string test = "Hello erase!"; test.erase(test.begin()); //test.erase(test.begin() + 1); //test.erase(test.end() - 1);
//删除指定字符
//test.erase(find(test.begin(), test.end(), 'l')); std::cout << "test: " << test.c_str() << std::endl;
【输出】
- ello erase!
- Hllo erase!
- Hello erase
- Helo erase!
(3)iterator erase ( iterator first, iterator last );
std::string test = "Hello erase!"; test.erase(test.begin(), test.begin() + 4); //test.erase(test.begin(), test.end() - 1); std::cout << "test: " << test.c_str() << std::endl;
【输出】
- o erase!
- !
(4)some feature and warning
- 搭配remove_if和lambda表达式
std::vector<int> c{ 1, 2, 3, 4, 5, 6, 7, 8, 9 }; int x = 5; c.erase(std::remove_if(c.begin(), c.end(), [x](int n) { return n < x; }), c.end()); std::cout << "c: "; for (auto i : c) { std::cout << i << ", "; }
【输出】c: 5, 6, 7, 8, 9
- 注意迭代器失效问题
std::vector<int> c{ 1, 2, 3, 4, 5, 6, 6, 6, 6, 7, 8, 9 }; //erase后it迭代器成为了野指针,这里指向了下一个指针。错误写法 for (auto it = c.begin(); it != c.end(); it++) { if (*it == 6) { c.erase(it); } } //正确写法 auto it = c.begin(); while (it != c.end()) { if (*it == 6) { it = c.erase(it); } else { it++; } } std::cout << "c: "; for (auto i : c) { std::cout << i << ", "; }
【输出】c: 1, 2, 3, 4, 5, 7, 8, 9