C++ STL 中的 forward_list::unique( )
本文将展示 C++ 中 forward_list::unique( ) 函数的运行情况。
正向列表是有序容器,允许在整个顺序中进行常量时间的插入和删除操作。正向列表实现为单链表。通过与每个元素关联到序列中下一个元素的链接来保持排序。
forward_list::unique( ) 是 c++ 标准库函数,用于从正向列表中删除所有重复元素。请注意,仅当元素与其后元素比较相等时,才会从 forward_list 容器中移除该元素。因此,此函数对于已排序的列表特别有用。
语法
Forwardlist_name.unique(binarypredicate name)
二进制谓词语法
bool 名称(数据类型 a,数据类型 b)
参数 - 此函数接受一个参数,该参数是一个二进制谓词,如果元素应被视为相等,则返回 true。
示例
Output – List : 4, 4, 17, 32, 45, 56, 56, 45, 32, 4, 17, 17 After Unique operation output is Unique list : 4, 17, 32, 45, 56 Output – List : 15.2, 74.0, 3.14, 15.2, 69.5, 74.0, 3.14, 18.5, 3.99 After Unique operation output is Unique list : 3.14, 3.99, 15.2, 18.5, 69.5, 74.0
可以遵循以下方法
首先,我们创建一个二进制谓词函数。
然后,初始化正向列表。
然后,定义 unique( ) 函数。
然后,在进行 unique 操作后打印正向列表。
通过使用上述方法,我们可以从 forward 列表中删除重复元素。
示例
// C++ code to demonstrate the working of forward_list::unique( )
#include<iostream.h>
#include<forward_list.h>
Using namespace std;
// function for binary predicate
bool cmp(int a, int b){
return (abs(a) == abs(b))
}
int main(){
// initializing the forward list
forward_list<int> List = { 2, 4, 6, 3, 5, 3, 4, 4, 9, 1, 6, 6, 2, 2, 9 }
cout<< " Elements of List:";
for( auto x = List.start(); x != List.end(); ++x )
cout<< *x << " ";
// defining of function that performs the Unique operation
List.unique();
cout<< “ Unique List :”;
for(auto x = List.start(); x != List.end(); ++x)
cout<< *x << " ";
return 0;
}输出
如果我们运行上述代码,则会生成以下输出
OUTPUT – List : 2, 4, 6, 3, 5, 4, 4, 9, 1, 6, 6, 2, 2, 9 Unique List : 1, 2, 3, 4, 5, 6, 9 OUTPUT – List : 15.2, 74.0, 3.14, 15.2, 69.5, 74.0, 3.14, 18.5, 3.99 Unique List : 3.14, 3.99, 15.2, 18.5, 69.5, 74.0
广告
数据结构
网络
RDBMS
操作系统
Java
iOS
HTML
CSS
Android
Python
C 编程
C++
C#
MongoDB
MySQL
Javascript
PHP