← Patterns

Check existence of a key

123456789101112#include <map> #include <string> int main() { std::map<std::string, int> m = {{"a", 1}, {"b", 2}, {"c", 3}}; if (m.count("b")) { // We know "b" is in m } }

This pattern is licensed under the CC0 Public Domain Dedication.

Requires c++11 or newer.

Intent

Check if a particular key is in an associative container.

Description

On line 6, we create a std::map as an example associative container and initialize it with key-value pairs.

On line 8, we count the number of occurrences of the key "b" in m by using the member function count. If "b" is in m, count will return 1; otherwise it will return 0.

Note: in C++14, an instance of the searched key will not be created if the container’s comparator is transparent and supports the appropriate comparison without conversions.

Contributors

  • Joseph Mansfield
  • Marco Arena

Last Updated

09 December 2017

Source

Fork this pattern on GitHub

Share