← Samples

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 sample is licensed under the CC0 Public Domain Dedication.

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

28 April 2015

Source

Fork this sample on GitHub

Share