Namespaces
Variants

std::ranges:: unique

From cppreference.net
Algorithm library
Constrained algorithms and algorithms on ranges (C++20)
Constrained algorithms, e.g. ranges::copy , ranges::sort , ...
Execution policies (C++17)
Non-modifying sequence operations
Batch operations
(C++17)
Search operations
Modifying sequence operations
Copy operations
(C++11)
(C++11)
Swap operations
Transformation operations
Generation operations
Removing operations
Order-changing operations
(until C++17) (C++11)
(C++20) (C++20)
Sampling operations
(C++17)

Sorting and related operations
Partitioning operations
Sorting operations
Binary search operations
(on partitioned ranges)
Set operations (on sorted ranges)
Merge operations (on sorted ranges)
Heap operations
Minimum/maximum operations
Lexicographical comparison operations
Permutation operations
C library
Numeric operations
Operations on uninitialized memory
Constrained algorithms
All names in this menu belong to namespace std::ranges
Non-modifying sequence operations
Modifying sequence operations
Partitioning operations
Sorting operations
Binary search operations (on sorted ranges)
Set operations (on sorted ranges)
Heap operations
Minimum/maximum operations
Permutation operations
Fold operations
Operations on uninitialized storage
Return types
ヘッダーで定義 <algorithm>
呼び出しシグネチャ
template < std:: permutable I, std:: sentinel_for < I > S, class Proj = std:: identity ,

std:: indirect_equivalence_relation < std :: projected < I, Proj >>
C = ranges:: equal_to >
constexpr ranges:: subrange < I >

unique ( I first, S last, C comp = { } , Proj proj = { } ) ;
(1) (C++20以降)
template < ranges:: forward_range R, class Proj = std:: identity ,

std:: indirect_equivalence_relation < std :: projected < ranges:: iterator_t < R > , Proj >>
C = ranges:: equal_to >
requires std:: permutable < ranges:: iterator_t < R >>
constexpr ranges:: borrowed_subrange_t < R >

unique ( R && r, C comp = { } , Proj proj = { } ) ;
(2) (C++20以降)
1) 範囲 [ first , last ) から連続する等価な要素群の各々について最初の要素以外をすべて除去し、部分範囲 [ ret , last ) を返す。ここで ret は範囲の新しい終端を指す終端イテレータである。
連続する2つの要素 *(i - 1) *i は、 std:: invoke ( comp, std:: invoke ( proj, * ( i - 1 ) ) , std:: invoke ( proj, * i ) ) == true の場合に等価と見なされます。ここで i は範囲 [ first + 1 , last ) 内のイテレータです。
2) (1) と同じですが、 r を範囲として使用し、あたかも ranges:: begin ( r ) first として、 ranges:: end ( r ) last として使用するかのように動作します。

このページで説明されている関数ライクなエンティティは、 アルゴリズム関数オブジェクト (非公式には niebloids として知られる)です。すなわち:

目次

翻訳内容: - 「Contents」→「目次」 - その他のC++関連用語(Parameters、Return value、Complexity、Notes、Possible implementation、Example、See also)は原文のまま保持 - HTMLタグ、属性、構造は完全に保持 - 番号部分は変更なし

パラメータ

first, last - 処理する要素の 範囲 を定義するイテレータ-センチネルペア
r - 処理する要素の範囲
comp - 投影された要素を比較する二項述語
proj - 要素に適用する投影

戻り値

戻り値は { ret, last } で、 ret は範囲の新しい終端を指すpast-the-endイテレータです。

計算量

空でない範囲の場合、対応する述語 comp の適用は正確に ranges:: distance ( first, last ) - 1 回であり、任意の射影 proj の適用はその2倍を超えない。

注記

削除は、範囲内の要素を移動代入によってシフトすることで行われ、削除されない要素が範囲の先頭に現れるようにします。残る要素の相対的な順序は保持され、コンテナの 物理的な サイズは変更されません。 [ ret , last ) 内のイテレータ(存在する場合)は依然としてデリファレンス可能ですが、要素自体は未規定の値を持ちます( MoveAssignable の事後条件に従います)。

ranges::unique への呼び出しは、時としてコンテナの erase メンバ関数の呼び出しに続けられます。これにより未規定の値が削除され、コンテナの 物理的 サイズが新しい 論理的 サイズに合うように縮小されます。これら2つの呼び出しを組み合わせることで、 Erase–remove イディオム を実現します。

実装例

struct unique_fn
{
    template<std::permutable I, std::sentinel_for<I> S, class Proj = std::identity,
             std::indirect_equivalence_relation<std::projected<I, Proj>>
                 C = ranges::equal_to>
    constexpr ranges::subrange<I>
        operator()(I first, S last, C comp = {}, Proj proj = {}) const
    {
        first = ranges::adjacent_find(first, last, comp, proj);
        if (first == last)
            return {first, first};
        auto i {first};
        ++first;
        while (++first != last)
            if (!std::invoke(comp, std::invoke(proj, *i), std::invoke(proj, *first)))
                *++i = ranges::iter_move(first);
        return {++i, first};
    }
    template<ranges::forward_range R, class Proj = std::identity,
             std::indirect_equivalence_relation<std::projected<ranges::iterator_t<R>, Proj>>
                 C = ranges::equal_to>
    requires std::permutable<ranges::iterator_t<R>>
    constexpr ranges::borrowed_subrange_t<R>
        operator()(R&& r, C comp = {}, Proj proj = {}) const
    {
        return (*this)(ranges::begin(r), ranges::end(r),
                       std::move(comp), std::move(proj));
    }
};
inline constexpr unique_fn unique {};

#include <algorithm>
#include <cmath>
#include <complex>
#include <iostream>
#include <vector>
struct id {
    int i;
    explicit id(int i) : i {i} {}
};
void print(id i, const auto& v)
{
    std::cout << i.i << ") ";
    std::ranges::for_each(v, [](auto const& e) { std::cout << e << ' '; });
    std::cout << '\n';
}
int main()
{
    // 重複要素を含むベクトル
    std::vector<int> v {1, 2, 1, 1, 3, 3, 3, 4, 5, 4};
    print(id {1}, v);
    // 連続する重複要素を削除
    const auto ret = std::ranges::unique(v);
    // vは現在 {1 2 1 3 4 5 4 x x x} を保持('x'は不定値)
    v.erase(ret.begin(), ret.end());
    print(id {2}, v);
    // ソート後にuniqueを適用して全ての重複を削除
    std::ranges::sort(v); // {1 1 2 3 4 4 5}
    print(id {3}, v);
    const auto [first, last] = std::ranges::unique(v.begin(), v.end());
    // vは現在 {1 2 3 4 5 x x} を保持('x'は不定値)
    v.erase(first, last);
    print(id {4}, v);
    // カスタム比較と射影を用いたunique
    std::vector<std::complex<int>> vc { {1, 1}, {-1, 2}, {-2, 3}, {2, 4}, {-3, 5} };
    print(id {5}, vc);
    const auto ret2 = std::ranges::unique(vc,
        // 実部の絶対値が等しい場合に複素数を等価とみなす:
        [](int x, int y) { return std::abs(x) == std::abs(y); }, // comp
        [](std::complex<int> z) { return z.real(); }             // proj
    );
    vc.erase(ret2.begin(), ret2.end());
    print(id {6}, vc);
}

出力:

1) 1 2 1 1 3 3 3 4 5 4
2) 1 2 1 3 4 5 4
3) 1 1 2 3 4 4 5
4) 1 2 3 4 5
5) (1,1) (-1,2) (-2,3) (2,4) (-3,5)
6) (1,1) (-2,3) (-3,5)

関連項目

連続する重複を含まない要素の範囲のコピーを作成する
(アルゴリズム関数オブジェクト)
等しい(または与えられた述語を満たす)最初の2つの隣接する要素を検索する
(アルゴリズム関数オブジェクト)
特定の条件を満たす要素を削除する
(アルゴリズム関数オブジェクト)
範囲内の連続する重複要素を削除する
(関数テンプレート)
連続する重複要素を削除する
( std::list<T,Allocator> の公開メンバ関数)
連続する重複要素を削除する
( std::forward_list<T,Allocator> の公開メンバ関数)