C++ remove erase 用法浅析
remove 用法浅析
写这篇浅析完全是意料之外的,只怪才疏学浅。
刷[Leetcode]929. Unique Email Addresses的时候不能用boost库,一脸懵逼,为了去除整个字符串中的“.”,boost库中就是一句话boost::erase_all(str, ‘.’),但是stl库中没有现成的接口可以使用,求助Google,发现了erase和remove结合使用可以达到目的;
local.erase(remove(local.begin(), local.end(), '.'), local.end()); // 删除local字符串中所有的'.'
复制代码
但是这样的用法没玩过,不是特别好理解,写个demo验证下,先看代码:
#include <algorithm>
#include <iostream>
#include <iterator>
#include <string>
using namespace std;
int main(int argc, char *argv[])
{
string str = "helloworld";
cout << "before remove: " << str << endl;
string::iterator ret_end = remove(str.begin(), str.end(), 'o'); // remove字符串中所有的‘o’,此时并没有真正删除
cout << "after remove: " << str << endl;
cout << "ret_end: ";
for (string::iterator i = str.begin(); i < ret_end; i++) {
cout << *i; // 这里打印的结果是从str的开头,到截止remove返回的应该结束的位置;
}
cout << endl;
str = "helloworld";
cout << "before erase: " << str << endl;
str.erase(remove(str.begin(), str.end(), 'o'), str.end());
cout << "after erase: " << str << endl;
return 0;
}
复制代码
先看下输出结果:
before remove: helloworld
after remove: hellwrldld
ret_end: hellwrld
before erase: helloworld
after erase: hellwrld
复制代码
具体看下remove的接口,cpluscplus手册上的链接std::remove
template <class ForwardIterator, class T>
ForwardIterator remove (ForwardIterator first, ForwardIterator last, const T& val);
复制代码
输入三个参数:迭代器起始,迭代器结束,要移除的值;
返回:迭代器,指向未移去的最后一个元素的下一个位置;
手册里面有一句解释:
The range between first and this iterator includes all the elements in the sequence that do not compare equal to val.
[first return)之间(不包含return指定的元素,到前一个截止),包含的是所有和val不等的元素,如上面demo中ret_end所示:
ret_end: hellwrld // first到ret_end包含所有不等于 ‘o’ 的序列, ret_end则指向的是‘ld’之后的那个‘l’
remove 实现
其实remove的实现,手册里面也有描述,就是需要理解一下
template <class ForwardIterator, class T>
ForwardIterator remove (ForwardIterator first, ForwardIterator last, const T& val)
{
ForwardIterator result = first;
while (first!=last) {
if (!(*first == val)) { // first不等于val时,result对应的值才会更新,并指向下一个元素
*result = move(*first);
++result;
}
++first;
}
return result;
}
复制代码
就到这。。顺便吐槽 一下csdn上面的一些帖子,看了好多篇,也没有说到点子上,还有解释错的,更是有抄错的。。