c++ - 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?
解决方案
如果我理解正确,您希望看到执行以下两个代码的相同输出字符串:
[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&
算法的参数,但在第一次删除操作时,引用指向的第一项的值被更改,并且删除算法失败。
推荐阅读
- android - 如何从 Android Studio 3.5.2 中的 RecyclerView.ViewHolder(itemView) 获取 Activity?
- amazon-web-services - 显示用户在线使用websocket、aws
- python - 如果存在则返回用户或创建新用户
- mongodb - 如何使用 ReactiveMongo 事务将文档写入 MongoDB?
- ios - 为什么我的 Podspec 会抛出多个:“执行策略异常注册失败并被跳过”注释?
- java - 如何将 FileChannel 对象转换为文件?
- knime - 加快 Knime 中的 Stanford Tagger
- java - 什么是信使队列?消息队列和信使队列是否相同?
- powershell - 从元数据自动命名文件的工具/脚本
- java - 在 selenium 中使用 for 循环时如何获取当前 url 并将其粘贴到邮件中(作为表格格式)