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。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。