Namespaces
Variants

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

ja.cppreference.net より

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

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

削除された要素へのイテレータおよび参照のみが無効になります。

1) 要素の比較に operator== を使用します。
2) 要素の比較に p を使用します。

対応する比較演算子が同値関係を確立しない場合、動作は未定義です。

パラメータ

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

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

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

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

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

戻り値

(なし)

(C++20まで)

削除された要素の数。

(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 <list>

std::ostream& operator<< (std::ostream& os, const std::list<int>& container)
{
    for (int val : container)
        os << val << ' ';
    return os << '\n';
}

int main()
{
    std::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

不具合報告

以下の動作変更の欠陥報告書は、以前に公開されたC++規格に対して遡及的に適用されました。

DR 適用対象 公開時の動作 正しい動作
LWG 1207 C++98 イテレータおよび/または参照が無効化されるかどうかが不明確
であった
削除された要素へのイテレータと参照のみを
無効化する

関連項目

範囲内の連続する重複要素を除去する
(関数テンプレート & アルゴリズム関数オブジェクト)
(C++20)