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::unordered_map::contains - cpprefjp C++日本語リファレンス

  1. リファレンス
  2. unordered_map
  3. unordered_map
  4. contains

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

履歴 編集

function
<unordered_map>

std::unordered_map::contains(C++20)

bool contains(const key_type& x) const;           // (1) C++20
constexpr bool contains(const key_type& x) const; // (1) C++26

template <class K>
bool contains(const K& k) const;           // (2) C++20
template <class K>
constexpr bool contains(const K& k) const; // (2) C++26

概要

指定されたキーに一致する要素がコンテナに含まれているかを判定する。

  • (1) : キーxを検索し、合致する要素が含まれるかを判定する
  • (2) : キーkを透過的に検索し、合致する要素が含まれるかを判定する

(2)の透過的な検索は、Pred::is_transparentおよびHash::is_transparentが定義される場合に有効になる機能であり、例としてunordered_map<string, int> m;に対してm.contains("key");のようにstring型のキーを持つ連想コンテナの検索インタフェースに文字列リテラルを渡した際、stringの一時オブジェクトが作られないようにできる。詳細はstd::hashクラスのページを参照。

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

  • (2) : Pred::is_transparent型およびHash::is_transparent型が定義されていること

戻り値

xとkを共通の変数aであるとして、以下と等価:

return find(a) != end();

計算量

  • 平均: 定数時間
  • 最悪: size について線形時間

例

#include <iostream>
#include <unordered_map>

int main()
{
  std::unordered_map<char, int> um = {
    {'a', 3},
    {'b', 1},
    {'c', 4}
  };

  // キー'b'の要素が含まれているか
  if (um.contains('b')) {
    std::cout << "contain" << std::endl;
  }
  else {
    std::cout << "doesn't contain" << std::endl;
  }
}

出力

contain

バージョン

言語

  • C++20

処理系

  • Clang: 9.0.1 ✅
  • GCC: 9.1 ✅
  • Visual C++: 2019 Update 1 ✅

参照

  • P0458R2 Checking for Existence of an Element in Associative Containers
  • P0919R3 Heterogeneous lookup for unordered containers
  • P3372R3 constexpr containers and adaptors
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.