首页 > 解决方案 > remove the character instance from string problem with remove

问题描述

I am facing a problem in removing all instances of a character from a string. As removal of characters is based on a loop condition, the results produced by C++ string function erase(or remove) are different. Have a look at the code:

int main()
    {
        string s="beabeefeab";
        string s2=s;
        cout<<"s[0] "<<s[0]<<endl;
        s.erase(remove(s.begin(),s.end(),'b'),s.end());   //statement 1
        cout<<s<<endl;
        s=s2;
        s.erase(remove(s.begin(),s.end(),s[0]),s.end());  //statement 2
        cout<<s<<endl;
        return 0;
    }

The output produced by statement 1 and statement 2 should be the same but turn out to be different. How and why?

标签: c++c++14

解决方案


如果我理解正确,您希望看到执行以下两个代码的相同输出字符串:

[1]
s = "beabeefeab";
s.erase(remove(s.begin(),s.end(),'b'),s.end());   //statement 1
cout << s << endl; // eaeefea

[2]
s = "beabeefeab";
s.erase(remove(s.begin(),s.end(),s[0]),s.end());  //statement 2
cout << s << endl; // should be eaeefea

您可以通过转换s[0]为 Rvalue -来实现它(char)s[0]

删除算法的第三个参数是const T&。当你通过'b'- Rvalue 被绑定到 const char&并且它对remove算法的整个执行有效。当您传递s[0]- Lvalue 时,Lvalue 绑定到const char&算法的参数,但在第一次删除操作时,引用指向的第一项的值被更改,并且删除算法失败。


推荐阅读