std::unorde...p::contains(3)
π¦ std::unordered_map::contains β the "wait, is it in there tho?" check
okay bestie, listen up, we're doing std::unordered_map::contains from the C++ Standard Libary (their spelling, not mine, don't come for me π
) and honestly? this one's a little icon. it answers the one question we all ask: is this key in the map or not. periodt.
β¨ NAME β¨
std::unordered_map::contains β literally std::unordered_map::contains, no notes. π
πΈ Synopsis πΈ
bool contains( const Key& key ) const; (1) (since C++20)
template< class K > (2) (since C++20)
bool contains( const K& x ) const;
so there's two flavors, both landing in C++20 (we love a recent queen π«Ά):
- checks if there's an element in the container whose key is equivalent to
key. that's it. that's the whole vibe. - checks if there's an element whose key compares equivalent to the value
x. fancy.
and now the important lowkey-flex: overload 2 only even participates in overload resolution if Hash::is_transparent and KeyEqual::is_transparent are valid and each denotes a type. not done yet β this also assumes that such a Hash is callable with both K and Key type, and that the KeyEqual is transparent, which, together, allows calling this function without constructing an instance of Key. no temp object, no construction, just vibes. iykyk β¨
π Parameters π
keyβ the key value of the element you're searching for. like, the thing you're looking for, bestie.xβ a value of any type that can be transparently compared with a key. any type! main character energy.
β Return value β
true if there is such an element, otherwise false. that's the whole story, no plot twist. π¦
π₯ Complexity π₯
Constant on average, worst case linear in the size of the container. so usually instant, but under the worst case it's giving "we're gonna be here a while" π
π Example π
// Run this code
#include <iostream>
#include <unordered_map>
int main()
{
std::unordered_map<int, char> example{{1, 'a'}, {2, 'b'}};
for (int x : {2, 5})
if (example.contains(x))
std::cout << x << ": Found\n";
else
std::cout << x << ": Not found\n";
}
π Output π
2: Found
5: Not found
look at her go. 2 ate. 5 did not. π
π See also π
findβ finds element with specific key (public member function)countβ returns the number of elements matching specific key (public member function)equal_rangeβ returns range of elements matching a specific key (public member function)
the whole friend group honestly. contains is just the one that tells you yes or no without extra drama π
fr fr that's the whole page β sourced from http://cppreference.com, dated 2024.06.10, std::unorde...p::contains(3), and yeah the title's abbreviated with ... up top, she's mysterious like that. go forth and check your keys, bestie π§π«
π¦ where this page comes from
- nixpkgs unstable: stdman 2024.07.05
- opensuse-leap 16.0: stdman 2024.07.05-bp160.1.9 Β· MIT
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash-1017 on : a language model's rewrite of the original, under its terms