在C ++ STL中列出unique()
给出的任务是显示STL中C++中的功能列表unique()函数。
什么是STL中的列表
列表是允许在任何地方按顺序进行恒定时间插入和删除的容器。列表被实现为双链表。列表允许不连续的内存分配。与数组,向量和双端队列相比,列表在容器中的任何位置执行元素的插入提取和移动效果更好。在列表中,对元素的直接访问很慢,并且列表与forward_list相似,但是转发列表对象是单个链接列表,并且只能迭代转发。
什么是唯一的()
列表unique()用于删除列表中所有重复的元素。
语法
list_name.unique(binarypredicate name)
二进制谓词的语法
布尔名称(data_typea,data_typeb)
参数
此函数接受单个参数,该参数是一个二进制谓词,如果元素应被视为相等,则返回true。
示例
输入列表-22679991055
输出新列表-2567910
输入列表-3.145.567.629.000.457.629.007.620.453.00
输出新列表-0.453.003.145.567.629.00
可以遵循的方法
首先,我们创建二进制谓词函数。
然后我们初始化列表。
然后,我们定义unique()函数。
然后我们在进行唯一操作后打印列表。
通过使用上述方法,我们可以从列表中删除重复的元素。
示例
/ / C++ code to demonstrate the working of list unique( ) function in STL
#include <iostream.h>
#include<list.h>
Using namespace std;
/ / function for binary predicate
Bool cmp(int a, int b){
Return (abs(a) == abs(b))
}
int main ( ){
List<int> list = { 13, 14, 13, 19, 20, 19, 15, 19, 20, 15, 15 };
/ / print the list
cout<< “ Elements in List: “;
for( auto x = List.begin( ); x != List.end( ); ++x)
cout<< *x << “ “;
/ / declaring unique( ) function
list.unique(cmp);
/ / printing new list after unique operation
cout<< “List after unique operation: “;
for( x=list.begin( ); x != list.end( ); ++x)
cout<< “ “<<*x;
return 0;
}输出结果
如果我们运行上面的代码,那么它将生成以下输出
Input - Element in List : 13 14 13 19 20 19 15 19 20 15 Output - List after unique operation : 13 14 15 19 20
示例
/ / C++ code to demonstrate the working of list unique( ) function in STL
#include<iostream.h>
#include<list.h>
Using namespace std;
/ / function for binary predicate
Bool cmp(float a, float b){
Return (abs(a) == abs(b))
}
int main ( ){
List <float>t; list = { 3.14, 5.56, 7.62, 9.00, 0.45, 7.62, 9.00, 7.62, 0.45, 3.00 };
/ / print the list
cout<< “ Elements in List: “;
for( auto x = List.begin( ); x != List.end( ); ++x)
cout<< *x << “ “;
/ / declaring unique( ) function
list.unique(cmp);
/ / printing new list after unique operation
cout<< “List after unique operation: ”;
for( x=list.begin( ); x != list.end( ); ++x)
cout<< “ “<<*x;
return 0;
}输出结果
如果我们运行上面的代码,那么它将生成以下输出
Input - Element in List: 3.14 5.56 7.62 9.00 0.45 7.62 9.00 7.62 0.45 3.00 Output - List after unique operation: 0.45 3.00 3.14 5.56 7.62 9.00