std::erase总结

Posted foreversdf

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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

 

以上是关于std::erase总结的主要内容,如果未能解决你的问题,请参考以下文章

循环在 std::list 上为迭代的 std::erase 挂起

如何在 CvPoint 和 int 的结构上应用 std::sort 和 std::erase?

python常用代码片段总结

BootStrap有用代码片段(持续总结)

BootStrap实用代码片段(持续总结)

回归 | js实用代码片段的封装与总结(持续更新中...)