其他答案已經解決了,你有特別的問題,但你應該知道,有解決您最實際的問題不同的方法:即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