转发列表 在STL实现中 单链表。 转发列表是在C++11中引入的,与其他容器相比,它在插入、删除和移动操作(如排序)中非常有用,并允许以时间常量插入和删除元素。它与列表的不同之处在于,转发列表只跟踪下一个元素的位置,而列表同时跟踪下一个和上一个元素。
null
转发列表::删除()
删除() 函数用于从转发列表中删除与作为函数参数给定的值相对应的所有值。此功能属于 头文件。 语法:
forwardlistname.remove(value)
参数: 要删除的元素的值作为参数传递。
结果: 移除容器中与作为参数传递的值相等的所有元素。
时间复杂性: 容器大小呈线性。
例如:
Input : forward_list forwardlist{1, 2, 3, 4, 5}; forwardlist.remove(4);Output : 1, 2, 3, 5Input : forward_list forwardlist{1, 2, 2, 2, 5, 6}; forwardlist.remove(2);Output : 1, 5, 6
错误和例外:
- 如果传递的值与转发列表类型不匹配,则显示错误。
- 如果转发列表功能的值和元素之间的比较没有引发任何异常,则不显示异常引发保证。
CPP
// CPP program to illustrate // Implementation of remove() function #include <forward_list> #include <iostream> using namespace std; // Driver Code int main() { forward_list< int > myforwardlist{ 1, 2, 2, 2, 5, 6, 7 }; myforwardlist. remove (2); for ( auto it = myforwardlist.begin(); it != myforwardlist.end(); ++it) cout << ' ' << *it; return 0; } |
输出
1 5 6 7
转发列表::删除如果()
删除_if() 函数用于从列表中删除与作为函数参数给定的谓词或条件相对应的所有值。该函数遍历列表容器的每个成员,并删除谓词返回true的所有元素。此功能属于 头文件。 语法:
forwardlistname.remove_if(predicate)
参数: 函数指针或函数对象形式的谓词作为参数传递。
结果: 移除容器中为谓词返回true的所有元素。
时间复杂性: 容器大小呈线性。
例如:
Input : forward_list forwardlist{1, 2, 3, 4, 5}; forwardlist.remove_if(odd);Output : 2, 4Input : forward_list forwardlist{1, 2, 2, 2, 5, 6, 7}; forwardlist.remove_if(even);Output : 1, 5, 7
错误和例外: 如果谓词函数功能不引发任何异常,则不显示异常引发保证。
CPP
// CPP program to illustrate implementation // of remove_if() function #include <forward_list> #include <iostream> using namespace std; // Predicate implemented as a function bool even( const int & value) { return (value % 2) == 0; } // Driver Code int main() { forward_list< int > myforwardlist{ 1, 2, 2, 2, 5, 6, 7 }; myforwardlist.remove_if(even); for ( auto it = myforwardlist.begin(); it != myforwardlist.end(); ++it) cout << ' ' << *it; return 0; } |
输出
1 5 7
remove_if()的应用: 给定一个整数列表,从列表中删除所有素数并打印列表。
Input : 2, 4, 6, 7, 9, 11, 13Output : 4, 6, 9
CPP
// CPP program to illustrate // Application of remove_if() function #include <forward_list> #include <iostream> using namespace std; // Predicate implemented as a function bool prime( const int & value) { int i; for (i = 2; i < value; i++) { if (value % i == 0) { return false ; ; break ; } } if (value == i) { return true ; ; } } // Driver Code int main() { forward_list< int > myforwardlist{ 2, 4, 6, 7, 9, 11, 13 }; myforwardlist.remove_if(prime); for ( auto it = myforwardlist.begin(); it != myforwardlist.end(); ++it) cout << ' ' << *it; return 0; } |
输出
4 6 9
如果您发现任何不正确的地方,或者您想分享有关上述主题的更多信息,请写下评论。
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END