Cro*_*dek 4 c++ string algorithm stl c++11
我想删除引用字符串传递的第一个和最后一个括号.不幸的是,我有条件地删除第一个和最后一个元素.我无法理解为什么remove_if不能像迭代器那样工作.
#include <iostream>
#include <algorithm>
using namespace std;
void print_wo_brackets(string& str){
auto detect_bracket = [](char x){ return(')' == x || '(' == x);};
if (!str.empty())
{
str.erase(std::remove_if(str.begin(), str.begin() + 1, detect_bracket));
}
if (!str.empty())
{
str.erase(std::remove_if(str.end()-1, str.end(), detect_bracket));
}
}
int main()
{
string str = "abc)";
cout << str << endl;
print_wo_brackets(str);
cout << str << endl;
string str2 = "(abc";
cout << str2 << endl;
print_wo_brackets(str2);
cout << str2 << endl;
return 0;
}
Run Code Online (Sandbox Code Playgroud)
abc)
ac <- HERE I expect abc
(abc
abc
Run Code Online (Sandbox Code Playgroud)
如果remove_if返回end迭代器,那么您将尝试擦除不存在的元素.您应该erase在两个地方使用版本范围:
void print_wo_brackets(string& str){
auto detect_bracket = [](char x){ return(')' == x || '(' == x);};
if (!str.empty())
{
str.erase(std::remove_if(str.begin(), str.begin() + 1, detect_bracket), str.begin() + 1);
}
if (!str.empty())
{
str.erase(std::remove_if(str.end()-1, str.end(), detect_bracket), str.end());
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
764 次 |
| 最近记录: |