C++ STL 中的 list unique( ) 函数
本任务演示 C++ STL 中 list unique( ) 函数的功能。
什么是 STL 中的 List?
List 是容器,允许在序列中的任何位置进行常数时间的插入和删除操作。List 以双向链表的形式实现。List 允许非连续内存分配。与数组、向量和双端队列相比,List 在容器的任何位置插入、提取和移动元素的性能更好。在 List 中,直接访问元素的速度较慢,并且 List 与 forward_list 类似,但 forward_list 对象是单向链表,只能向前迭代。
什么是 unique( )?
list unique( ) 用于删除列表中的所有重复元素。
语法
list_name.unique(binarypredicate name)
二元谓词的语法
Bool name(data_type a, data_type b)
参数
此函数接受一个参数,该参数是一个二元谓词,如果元素应被视为相等,则返回 true。
示例
输入 列表 - 2 2 6 7 9 9 9 10 5 5
输出 新列表 - 2 5 6 7 9 10
输入 列表 - 3.14 5.56 7.62 9.00 0.45 7.62 9.00 7.62 0.45 3.00
输出 新列表 - 0.45 3.00 3.14 5.56 7.62 9.00
可采用的方法
首先,我们创建一个二元谓词函数。
然后我们初始化列表。
然后我们定义 unique( ) 函数。
然后我们打印 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
广告
数据结构
网络
关系数据库管理系统 (RDBMS)
操作系统
Java
iOS
HTML
CSS
Android
Python
C 语言编程
C++
C#
MongoDB
MySQL
Javascript
PHP