35 lines · plain
1.. title:: clang-tidy - readability-container-contains2 3readability-container-contains4==============================5 6Finds usages of ``container.count()`` and7``container.find() == container.end()`` which should be replaced by a call to8the ``container.contains()`` method.9 10Whether an element is contained inside a container should be checked with11``contains`` instead of ``count``/``find`` because ``contains`` conveys the12intent more clearly. Furthermore, for containers which permit multiple entries13per key (``multimap``, ``multiset``, ...), ``contains`` is more efficient than14``count`` because ``count`` has to do unnecessary additional work.15 16Examples:17 18====================================== =====================================19Initial expression Result20-------------------------------------- -------------------------------------21``myMap.find(x) == myMap.end()`` ``!myMap.contains(x)``22``myMap.find(x) != myMap.end()`` ``myMap.contains(x)``23``myStr.find(x) != std::string::npos`` ``myStr.contains(x)``24``if (myMap.count(x))`` ``if (myMap.contains(x))``25``bool exists = myMap.count(x)`` ``bool exists = myMap.contains(x)``26``bool exists = myMap.count(x) > 0`` ``bool exists = myMap.contains(x)``27``bool exists = myMap.count(x) >= 1`` ``bool exists = myMap.contains(x)``28``bool missing = myMap.count(x) == 0`` ``bool missing = !myMap.contains(x)``29====================================== =====================================30 31This check will apply to any class that has a ``contains`` method, notably32including ``std::set``, ``std::unordered_set``, ``std::map``, and33``std::unordered_map`` as of C++20, and ``std::string`` and34``std::string_view`` as of C++23.35