STL删除元素
remove() & remove_if()
- remove和remove_if只是通过迭代器的指针向前移动来删除,将没有被删除的元素放在链表的前面,并返回一个指向新的尾值的迭代器。由于remove()函数不是成员,因此不能调整链表的长度。
- remove函数原型如下:
template< class ForwardIt, class T > ForwardIt remove(ForwardIt first, ForwardIt last, const T& value) { first = std::find(first, last, value); if (first != last) for(ForwardIt i = first; ++i != last; ) if (!(*i == value)) *first++ = std::move(*i); return first; }
- remove_if也类似,只是多了一个函数作为判断,传入容器元素,返回true的元素则被remove(移动到后面去)。
// 原型: remove_if(beg, end, op); // Example bool IsSpace(char x) { return x == ' '; } string str2 = "Text with some spaces"; // 处理前:"Text with some spaces" str2.erase(remove_if(str2.begin(), str2.end(), IsSpace), str2.end()); // 处理后:"Textwithsomespaces"
erase-remove用法
-
remove()函数并不是真正的删除,要想真正删除元素则可以使用erase()或者resize()函数。用法如下:
string str1 = "Text with some spaces"; str1.erase( std::remove(str1.begin(), str1.end(), ' '), //返回把空格移到后面的第一个迭代器 str1.end() //删除两个迭代器之间的空格 ); // ,结果:"Textwithsomespaces"