這裏有兩個有用的小功能:
template<class C, class F>
bool remove_erase_if(C& c, F&& f) {
using std::begin; using std::end;
auto it = std::remove_if(begin(c), end(c), std::forward<F>(f));
if (it == c.end())
return false;
c.erase(it, c.end());
return true;
}
template<class C, class T>
bool remove_erase(C& c, T&& t) {
using std::begin; using std::end;
auto it = std::remove(begin(c), end(c), std::forward<T>(t));
if (it == c.end())
return false;
c.erase(it, c.end());
return true;
}
這些既採取的容器中,並且或者一個測試或一個元素。
然後,他們刪除並擦除所有通過測試的元素,或等於元素。
您的代碼模擬了上述代碼的remove
部分,並沒有執行erase
部分。所以剩下的角色依然存在。
remove
(或您的代碼)只是將所有「保留」的數據移動到容器的前面。最後剩下的東西......留在那裏。步驟erase
然後告訴容器之後的東西應該丟棄你保留的東西。如果你不放棄它,那它......仍然......並且你得到了你的錯誤。
通過以上兩個功能,你可以這樣做:
int main() {
std::string s = "What is your name?";
remove_erase(s, ' ');
std::cout << s << '\n';
}
和你做。
另外,using namespace std;
通常是bad idea。並且std::endl
強制緩衝區刷新,所以我更喜歡'\n'
。最後,system("pause")
可以通過在一個模式下運行IDE來模擬,使您的命令窗口保持打開狀態,而不是將其添加到您的代碼中Ctrl-F5。
您用較短的輸出覆蓋輸入,但長度保持不變。 –
啊,有道理。 對不起,我是C++的新手,你能告訴我這個循環如何用正常的循環寫入嗎? –
您可以跟蹤空格的數量,然後在最後調整字符串的大小。 – u8sand