forward_list::unique()是C++ STL中的内置函数,可从forward_list中删除所有连续的重复元素。它使用二进制谓词进行比较。
用法:
forwardlist_name.unique(BinaryPredicate name)
参数:该函数接受单个参数,该参数是一个二进制谓词,如果元素应被视为相等,则返回true。它具有以下语法:
bool name(data_type a, data_type a)
返回值:该函数不返回任何内容。
// C++ program to illustrate the
// unique() function
#include <bits/stdc++.h>
using namespace std;
// Function for binary_predicate
/*bool compare(int a, int b)
{
return (abs(a) == abs(b));
}
// This function can also be used and passed inside
// unique(), to get the same result
*/
int main()
{
forward_list<int> list = { 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 2, 4, 4 };
cout << "List of elements before unique operation is:";
// starts from the first element of the list to the last
for (auto it = list.begin(); it != list.end(); ++it)
cout << *it << " ";
// unique operation on forward list
list.unique();
cout << "\nList of elements after unique operation is:";
// starts from the first element of the list to the last
for (auto it = list.begin(); it != list.end(); ++it)
cout << *it << " ";
return 0;
}
输出:
List of elements before unique operation is:1 1 1 1 2 2 2 2 3 3 3 2 4 4 List of elements after unique operation is:1 2 3 2 4
相关用法
注:本文由纯净天空筛选整理自Twinkl Bajaj大神的英文原创作品 forward_list::unique() in C++ STL。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。