GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • cpprefjp - C++日本語リファレンス
  • GitHub Project

This view

  • Original page
  • New address

GeezerVison is showing cpprefjp.github.io — std::sortable - cpprefjp C++日本語リファレンス

  1. リファレンス
  2. iterator
  3. sortable

最終更新日時: 2026年09月19日 21時31分51秒 (JST)
rotarymars が更新

履歴 編集

concept
<iterator>

std::sortable(C++20)

namespace std {
  template<class I, class R = ranges::less, class P = identity>
  concept sortable =
    permutable<I> &&
    indirect_strict_weak_order<R, projected<I, P>>;
}

概要

sortableは、イテレータ型Iの参照する範囲をRによる比較関数によってソートできる事を表すコンセプトである。
また、その際にイテレータに対して任意の射影操作(P)を指定する事ができる。

これは、sortのような操作を可能とするための最小の要求である。

例

#include <iostream>
#include <concepts>
#include <iterator>
#include <vector>

template<std::bidirectional_iterator I, std::sentinel_for<I> S, typename R = std::ranges::less, typename P = std::identity>
  requires std::sortable<I, R, P> // ソートに必要な操作を制約する
void bubble_sort(I it, S end, R comp = {}, P proj = {}) {
  if (it == end) return;

  int count{};

  for (auto loopend = std::ranges::prev(end, 1); it != loopend; std::ranges::advance(loopend, -count)) {
    count = 0;
    for (auto current = it; current != loopend; ++current) {
      if (auto next = std::ranges::next(current); comp(proj(*current), proj(*next))) {
        //                                        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ 
        //                                        ↑これと
        ++count;
      } else {
        std::iter_swap(current, next);  // これ
        count = 0;
      }
    }
    if (count == 0) ++count;
  }
}

int main() {

  std::vector<int> vec = {9, 5, 1, 2, 4, 6, 3, 0, 8, 7};
  bubble_sort(vec.begin(), vec.end());

  for (auto n : vec) {
    std::cout << n;
  }
}

出力

0123456789

バージョン

言語

  • C++20

処理系

  • Clang: 16.0.6 ✅
  • GCC: 10.1 ✅
  • Visual C++: 2019 Update 6 ✅

関連項目

  • C++20 コンセプト
  • sort

参照

  • P0896R4 The One Ranges Proposal (was Merging the Ranges TS)
You are visitor 01402503 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.