• Class / Function / Type

      std::
    • Header file

      <>
    • Other / All

    最終更新日時(UTC):
    が更新

    履歴 編集

    function
    <iterator>

    std::basic_const_iterator::operator-

    template<sized_sentinel_for<Iterator> S>
    constexpr difference_type operator-(const S& y) const;  // (1)
    
    template<not-a-const-iterator S>
      requires sized_sentinel_for<S, Iterator>
    friend constexpr difference_type operator-(const S& x, const basic_const_iterator& y);  // (2) 非メンバ関数
    

    概要

    basic_const_iteratorの間、もしくはIteratorに対応する番兵との間の距離を計算する。

    basic_const_iterator<Iterator>のオブジェクトをiIteratorに対応する番兵型のオブジェクトをsとすると

    テンプレートパラメータ制約

    not-a-const-iterator<I>Ibasic_const_iteratorの特殊化ではない場合にtrueとなる説明専用のコンセプトである。

    効果

    ラップしているイテレータをcurrent_メンバ変数に保持するとして

    • (1) : 以下と等価

      return current_ - y;
      

    • (2) : 以下と等価

      return x - y.current_;
      

    備考

    (2)の関数はHidden friendsとして定義される。

    #include <iostream>
    #include <iterator>
    #include <vector>
    
    int main() {
      std::vector vec = {1, 2, 3, 4, 5};
    
      std::basic_const_iterator cit = vec.begin();
      auto se = vec.end();
    
      // 元のイテレータの番兵との間で距離計算
      std::cout << (cit - se) << '\n';
      std::cout << (se - cit) << '\n';
    
      std::basic_const_iterator cse = se;
    
      // basic_const_iterator同士で距離計算
      // (1) -> (2)と呼ばれることで内部イテレータ同士の距離計算を行う
      std::cout << (cit - cse) << '\n';
      std::cout << (cse - cit) << '\n';
    }
    

    出力

    -5
    5
    -5
    5
    

    バージョン

    言語

    • C++23

    処理系

    参照