名前空間
変種
操作

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

From cppreference.com
< cpp‎ | container‎ | list
 
 
 
 
(1)
void unique();
(C++20まで)
size_type unique();
(C++20以降)
(2)
template< class BinaryPredicate >
void unique( BinaryPredicate p );
(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 の) Type1Type2 のすべての値を受け入れられる必要がある (したがって、Type1 & は許可されない。また、Type1 の場合、ムーブがコピーと同等でない限り、Type1 も許可されない。(C++11以降))。
Type1 および Type2 の型は、list<T,Allocator>::const_iterator のオブジェクトを間接参照してから、それらの両方に暗黙的に変換できる必要があります。

型要件
-
BinaryPredicateBinaryPredicate の要件を満たす必要があります。

[編集] 戻り値

(なし)

(C++20まで)

削除された要素の数。

(C++20以降)

[編集] 計算量

もし empty()true であれば、比較は実行されません。

それ以外の場合、Nstd::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, std::list<int> const& 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 イテレータが
または参照が無効になるかどうかは不明でした
削除された要素へのイテレータと
参照のみが無効になります

[編集] 関連項目

範囲内の連続する重複要素を削除する
(関数テンプレート) [編集]
English 日本語 中文(简体) 中文(繁體)