C++ STL 中的 forward_list::unique( )

c++server side programmingprogramming更新于 2025/4/23 17:07:17

给出的任务是展示 C++ 中 forward_list::unique( ) 函数的工作原理。

前向列表是序列容器,允许在序列中的任何位置进行常量时间插入和删除操作。前向列表实现为单链表。通过将每个元素与序列中的下一个元素链接关联来保持顺序。

forward_list::unique( ) 是 C++ 标准库函数中的一个函数,用于从前向列表中删除所有重复元素。请注意,只有当元素与其紧邻的元素相等时,才会从 forward_list 容器中删除该元素。因此,此函数对于排序列表特别有用。

语法

Forwardlist_name.unique(binarypredicate name)

二元谓词的语法

bool name(data type a, data type b)

参数 − 此函数接受单个参数,该参数是二元谓词,如果元素应被视为相等,则返回 true。

示例

输出 – 列表:4、4、17、32、45、56、56、45、32、4、17、17
   Unique 操作后输出为
      唯一列表:4、17、32、45、56
输出 – 列表:15.2、74.0、3.14、15.2、69.5、74.0、3.14、18.5、3.99
   Unique 操作后输出为
     唯一列表:3.14、3.99、15.2、18.5、69.5、74.0

可以遵循方法

  • 首先,我们创建二元谓词函数。

  • 然后,我们初始化前向列表。

  • 然后,我们定义 unique() 函数。

  • 然后,我们在唯一操作之后打印前向列表。

通过使用上述方法,我们可以从前向列表中删除重复的元素。

示例

// C++ 代码演示 forward_list::unique() 的工作方式
#include<iostream.h>
#include<forward_list.h>
Using namespace std;
// 二元谓词函数
bool cmp(int a, int b){
   return (abs(a) == abs(b))
}
int main(){
   // 初始化转发列表
   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 << " ";
   // 定义执行唯一操作的函数
   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

相关文章