其他答案已经解决了,你有特别的问题,但你应该知道,有解决您最实际的问题不同的方法:即fullfill条件擦除元素。可与删除迎刃而解/擦除成语:
// C++0x enabled compiler
str.erase(
std::remove_if(str.begin(), str.end(),
[](char ch) { return !isalpha(ch) && !isdigit(ch) && ch != '-' }),
str.end());
虽然这可能看起来很麻烦,首先,当你看到它了几次就不再是令人惊奇的,而且它是一个有效的从矢量或字符串中删除元素的方法。
如果你的编译器没有拉姆达支持,那么你可以创建一个仿函数,并把它作为第三个参数remove_if
:
// at namespace level, sadly c++03 does not allow you to use local classes in templates
struct mycondition {
bool operator()(char ch) const {
return !isalpha(ch) && !isdigit(ch) && ch != '-';
}
};
// call:
str.erase(
std::remove_if(str.begin(), str.end(), mycondition()),
str.end());
你为什么标记该C? – GManNickG 2011-03-24 17:08:46
你真的不需要isalpha和isdigit检查你是否要检查后面的特定字符 – AJG85 2011-03-24 17:17:59