名前空間
変種
操作

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

From cppreference.com
 
 
 
 
(1)
void unique();
(C++11以降)
(C++20まで)
size_type unique();
(C++20以降)
(2)
template< class BinaryPredicate >
void unique( BinaryPredicate p );
(C++11以降)
(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の型は、forward_list<T,Allocator>::const_iteratorのオブジェクトを逆参照してから、それらの両方に暗黙的に変換できる必要があります。​

型要件
-
BinaryPredicateは、BinaryPredicateの要件を満たす必要があります。

[編集] 戻り値

(なし)

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

[編集] 関連項目

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