Libreria C ++ Forward_list - funzione unique ()

Descrizione

La funzione C ++ std::forward_list::unique()rimuove tutti gli elementi duplicati consecutivi da forward_list. Usa predicato binario per il confronto.

Dichiarazione

Di seguito è riportata la dichiarazione per la funzione std :: forward_list :: unique () nell'intestazione std :: forward_list.

C ++ 11

template <class BinaryPredicate>
void unique (BinaryPredicate binary_pred);

Parametri

binary_pred- predicato binario che restituisce vero se gli elementi devono essere trattati come uguali. Ha il seguente prototipo.

bool pred(const Type1 &arg1, const Type2 &arg2);

Valore di ritorno

Nessuna

Eccezioni

Questa funzione membro non genera mai eccezioni.

Complessità temporale

Lineare cioè O (n)

Esempio

L'esempio seguente mostra l'utilizzo della funzione std :: forward_list :: unique ().

#include <iostream>
#include <forward_list>

using namespace std;

bool cmp_fun(int a, int b) {
   return (abs(a) == abs(b));
}

int main(void) {

   forward_list<int> fl = {1, -1, -1, -1, 2, 2, -2, -2, 3, -4, 4, -5, -5, 5};

   cout << "List elements before unique operation" << endl;
   for (auto it = fl.begin(); it != fl.end(); ++it)
      cout << *it << endl;

   fl.unique(cmp_fun);

   cout << "List elements after unique operation" << endl;
   for (auto it = fl.begin(); it != fl.end(); ++it)
      cout << *it << endl;

   return 0;
}

Compiliamo ed eseguiamo il programma sopra, questo produrrà il seguente risultato:

List elements before unique operation
1
-1
-1
-1
2
2
-2
-2
3
-4
4
-5
-5
5
List elements after unique operation
1
2
3
-4
-5