C++ STL中的forward_list::remove()和forward_list::remove_if()
forward_list是C++ STL中的一个单向链表容器,它提供了许多对链表进行操作的函数。其中,remove()和remove_if()是用来从链表中删除元素的函数,二者的区别在于删除的条件不同。
forward_list::remove()
remove()函数可以删除链表中所有与给定参数相等的元素,其函数原型如下:
void remove(const T& value);
其中,T为forward_list存储的元素的数据类型。例如,如果我们有一个forward_list<int>类型的链表,想要删除所有等于3的元素,可以这样写:
#include <forward_list>
#include <iostream>
int main() {
std::forward_list<int> l = {1,2,3,4,3,5,6};
l.remove(3);
for(auto it = l.begin(); it != l.end(); ++it) {
std::cout << *it << " ";
}
return 0;
}
输出结果为1 2 4 5 6,可见所有等于3的元素已被删除。
forward_list::remove_if()
remove_if()函数可以删除链表中所有符合给定条件的元素,其函数原型如下:
template <class UnaryPredicate>
void remove_if(UnaryPredicate p);
其中,UnaryPredicate为一个一元函数对象,对于链表中的每个元素,调用该函数后返回true的元素将被删除。
例如,如果我们有一个forward_list<int>类型的链表,想要删除所有大于3的元素,可以这样写:
#include <forward_list>
#include <iostream>
int main() {
std::forward_list<int> l = {1,2,3,4,3,5,6};
l.remove_if([](const int& n){return n>3;});
for(auto it = l.begin(); it != l.end(); ++it) {
std::cout << *it << " ";
}
return 0;
}
输出结果为1 2 3 3,可见所有大于3的元素已被删除。
forward_list::erase_after()
与remove()和remove_if()类似,erase_after()函数也可以删除链表中的元素。该函数的原型如下:
iterator erase_after(const_iterator position);
其中,position为待删除元素的前一元素的迭代器。该函数将删除position之后的元素,并返回删除后的下一个元素的迭代器。
例如,如果我们有一个forward_list<int>类型的链表,想要删除第二个元素,可以这样写:
#include <forward_list>
#include <iostream>
int main() {
std::forward_list<int> l = {1,2,3,4,5};
auto it = l.erase_after(l.begin());
std::cout << *it << std::endl; // 输出3
for(auto it = l.begin(); it != l.end(); ++it) {
std::cout << *it << " ";
}
return 0;
}
输出结果为3 4 5,可见第二个元素(也即值为2的元素)已被删除。
结论
forward_list提供了删除链表中元素的多种方式,remove()和remove_if()能够批量删除元素,而erase_after()则适用于单个元素的删除。在使用时需根据需要选择合适的函数。
极客笔记