码迷,mamicode.com
首页 > 其他好文 > 详细

std::erase总结

时间:2020-05-27 12:27:35      阅读:65      评论:0      收藏:0      [点我收藏+]

标签:div   begin   position   code   string   ast   rem   ==   last   

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总结

标签:div   begin   position   code   string   ast   rem   ==   last   

原文地址:https://www.cnblogs.com/foreversdf/p/12971171.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!