给出的任务是显示C ++中forward_list::unique()函数的工作。
转发列表是序列容器,允许在序列中的任何位置进行恒定时间的插入和擦除操作。转发列表被实现为单链接列表。通过与到序列中下一个元素的链接的每个元素的关联来保持顺序。
forward_list::unique()是c ++标准库函数中的一个函数,用于从转发列表中删除所有重复的元素。请注意,只有将元素与立即比较的元素相等才将其从forward_list容器中删除。因此,此功能对于排序列表特别有用。
Forwardlist_name.unique(binarypredicate name)
布尔名称(数据类型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()函数。
然后我们在进行唯一操作后打印转发列表。
通过使用上述方法,我们可以从转发列表中删除重复元素。
// C++ code to demonstrate the working of 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<< " 列表元素:"; 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