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

履歴 編集

function template
<unordered_set>

std::operator==(C++11)

namespace std {
  template <class Key, class Hash, class Pred, class Allocator>
  bool operator==(const unordered_set<Key, Hash, Pred, Allocator>& a,
                  const unordered_set<Key, Hash, Pred, Allocator>& b); // (1) C++11
}

概要

unordered_set オブジェクトを等値比較する。

要件

  • a.key_eq()b.key_eq() は同じふるまいをすること。
  • key_type の等値比較演算子(operator==)で等値と判定された 2 つのオブジェクトは、key_eq() でも等値と判定されること。

戻り値

以下の両方を満たす場合 true、そうでない場合 false

  • a.size() == b.size() である。
  • 一方のコンテナの全ての要素が、他方のコンテナにも存在する。ここで、存在するとは、key_type の等値比較演算子(operator==)で等値と判定されるということである。

計算量

  • 平均: size() に対して線形時間
  • 最悪: size() に対して二乗時間

備考

  • 本関数は、コンテナ内の要素の比較に key_eq() で返されるキー比較用関数オブジェクトを使用しないことに注意。
  • 本関数は、標準コンテナの要件を満たさない。これは、標準コンテナの要件では operator!=iteratorstd::equal を用いて定義されているためである。しかし、本関数の戻り値は、両方のコンテナが同じ要素を保持しているという意味においては、標準コンテナと同様とも考えることができる。
  • この演算子によって、以下の演算子が使用可能になる (C++20):
    • operator!=

#include <iostream>
#include <string>
#include <unordered_set>
#include <iterator>
#include <algorithm>

template <class C>
void print(const std::string& label, const C& c, std::ostream& os = std::cout)
{
  os << label << ":";
  std::copy(std::begin(c), std::end(c), std::ostream_iterator<typename C::value_type>(os, ", "));
  os << std::endl;
}

int main()
{
  std::cout << std::boolalpha;

  std::unordered_set<int> us1{ 1, 2, 3, };
  std::unordered_set<int> us2{ 4, 5, 6, };
  std::unordered_set<int> us3{ 1, 2, 3, };

  print("us1", us1);
  print("us2", us2);
  print("us3", us3);

  std::cout << "us1 == us2:" << (us1 == us2) << std::endl;
  std::cout << "us1 == us3:" << (us1 == us3) << std::endl;
}

出力

us1:3, 2, 1,
us2:6, 5, 4,
us3:3, 2, 1,
us1 == us2:false
us1 == us3:true

注:unordered_set は非順序連想コンテナであるため、出力順序は無意味であることに注意

バージョン

言語

  • C++11

処理系

実装例

namespace std {
  template <class Key, class Hash, class Pred, class Allocator>
  bool operator==(const unordered_set<Key, Hash, Pred, Allocator>& a,
                  const unordered_set<Key, Hash, Pred, Allocator>& b)
  {
    if (a.size() != b.size())
      return false;

    for (auto it = a.begin(), ae = a.end(), be = b.end(); it != ae; ++it) {
      auto f = b.find(*it);
      if (f == be || !bool(*f == *it))
        return false;
    }

    return true;
  }
}

関連項目

名前 説明
operator!= 非等値比較

参照