Namespaces
Variants

std::forward_list<T,Allocator>:: unique

From cppreference.net

(1)
void unique ( ) ;
(C++11以降)
(C++20まで)
size_type unique ( ) ;
(C++20以降)
(constexpr C++26以降)
(2)
template < class BinaryPred >
void unique ( BinaryPred p ) ;
(C++11以降)
(C++20まで)
template < class BinaryPred >
size_type unique ( BinaryPred p ) ;
(C++20以降)
(constexpr C++26以降)

コンテナからすべての 連続した 重複要素を削除します。等しい要素のグループごとに最初の要素のみが残されます。

1) 次と等価 unique ( std:: equal_to < T > ( ) ) (C++14まで) unique ( std:: equal_to <> ( ) ) (C++14以降)
2) 要素の比較に p を使用します。
p が同値関係を確立しない場合、動作は未定義です。

削除された要素に対するイテレータと参照のみを無効化します。

目次

パラメータ

p - 要素が等しいと扱われるべき場合に​ true を返す二項述語。

述語関数のシグネチャは以下と同等であるべきです:

bool pred ( const Type1 & a, const Type2 & b ) ;

シグネチャが const & を持つ必要はありませんが、関数は渡されたオブジェクトを変更してはならず、 値カテゴリ に関係なく(したがって、 Type1 & は許可されません 、また Type1 も、 Type1 に対してムーブがコピーと等価でない限り許可されません (C++11以降) )、型 Type1 Type2 のすべての値を受け入れられる必要があります。
Type1 Type2 は、 forward_list < T,Allocator > :: const_iterator 型のオブジェクトが間接参照され、それら両方に暗黙的に変換可能である必要があります。 ​

型要件
-
BinaryPred BinaryPredicate の要件を満たさなければなりません。

戻り値

(なし)

(until C++20)

削除された要素の数。

(since C++20)

計算量

empty() true の場合、比較は実行されません。

それ以外の場合、 N std:: distance ( begin ( ) , end ( ) ) として定義する:

1) 正確に N-1 回の比較を operator == を使用して行う。
2) 厳密に N-1 回の述語 p の適用。

注記

機能テスト マクロ 標準 機能
__cpp_lib_list_remove_return_type 201806L (C++20) 戻り値の型を変更

#include <iostream>
#include <forward_list>
std::ostream& operator<< (std::ostream& os, std::forward_list<int> const& container)
{
    for (int val : container)
        os << val << ' ';
    return os << '\n';
}
int main()
{
    std::forward_list<int> c{1, 2, 2, 3, 3, 2, 1, 1, 2};
    std::cout << "Before unique(): " << c;
    const auto count1 = c.unique();
    std::cout << "After unique():  " << c
              << count1 << " elements were removed\n";
    c = {1, 2, 12, 23, 3, 2, 51, 1, 2, 2};
    std::cout << "\nBefore unique(pred): " << c;
    const auto count2 = c.unique([mod = 10](int x, int y)
    {
        return (x % mod) == (y % mod);
    });
    std::cout << "After unique(pred):  " << c
              << count2 << " elements were removed\n";
}

出力:

Before unique(): 1 2 2 3 3 2 1 1 2
After unique():  1 2 3 2 1 2
3 elements were removed
Before unique(pred): 1 2 12 23 3 2 51 1 2 2
After unique(pred):  1 2 23 2 51 2
4 elements were removed

関連項目

連続する重複要素を範囲から削除する
(関数テンプレート)