注意,使用remove后需要再使用erase才能达成我们想要的移除效果!
这是因为remove只是把数据移到容器的末尾,并没有真正删除,此时我们根据remove的返回值——也就是指向最前面那个我们需要删除数据的迭代器,再调用一次erase即可。
下列代码从 string 移除所有空格,通过迁移所有非空格字符到左侧,再擦除其他内容。这是擦除移除手法的样例。
#include <algorithm>
#include <string>
#include <iostream>
#include <cctype>
using namespace std;
int main()
{
string str1 = "Text with some spaces";
str1.erase(remove(str1.begin(), str1.end(), ' '),
str1.end());
cout << str1 << endl;
}
输出:
Textwithsomespaces
可见str1的空格都被删除了