std::map::value_comp(3)
β¨ std::map::value_comp β¨
okay bestie, welcome to the std::map corner of the C++ Standard Library β this one's about std::map::value_comp, and honestly? it's giving "small but mighty" π
πΈ Synopsis πΈ
std::map::value_compare value_comp() const;
So here's the tea π: this bad boy hands you back a function object β and that function object compares objects of type std::map::value_type, aka those cute little key-value pairs π. How does it compare them? It peeks at the first component of each pair, and it does that by using key_comp. like, it outsources the key comparison to key_comp and just compares the firsts. iconic delegation honestly π
π¦ Parameters π¦
(none) β nope, nada, zero arguments, she takes nothing and needs nothing π
π Return value π
The value comparison function object. that's it, that's the gift π
β Complexity β
Constant. O(1) energy β instant, no notes, ate and left no crumbs π₯
π Example π
ok so run this code, trust me:
#include <iostream>
#include <map>
#include <utility>
// Example module 97 key compare function
struct ModCmp
{
bool operator()(int lhs, int rhs) const
{
return (lhs % 97) < (rhs % 97);
}
};
int main()
{
std::map<int, char, ModCmp> cont;
cont = {{1, 'a'}, {2, 'b'}, {3, 'c'}, {4, 'd'}, {5, 'e'}};
auto comp_func = cont.value_comp();
for (const std::pair<int, char> val = {100, 'a'}; auto it : cont)
{
const bool before = comp_func(it, val);
const bool after = comp_func(val, it);
std::cout << '(' << it.first << ',' << it.second << ") ";
if (!before && !after)
std::cout << "equivalent to key (" << val.first << ")\n";
else if (before)
std::cout << "goes before key (" << val.first << ")\n";
else if (after)
std::cout << "goes after key (" << val.first << ")\n";
else
std::unreachable();
}
}
like, look at that ModCmp struct β it's a custom "module 97" key compare function, and it's lowkey the main character of this whole example π 100 and 3 are equivalent under % 97 (both stay 3), which is exactly why the (3,c) line says "equivalent" instead of before/after. slay π
π Output:
(1,a) goes before key (100)
(2,b) goes before key (100)
(3,c) equivalent to key (100)
(4,d) goes after key (100)
(5,e) goes after key (100)
π See also π
key_compβ returns the function that compares keys (it's a public member function, bestie) π«Ά
so yeah, that's the whole vibe: value_comp gives you a comparator that's obsessed with the key half of every pair, and it does it in constant time, no cap π
happy mapping, babe! πβ¨
β sign-off time: this lil page comes to you from cppreference.com (the source), dated 2024.06.10 β catch you on the next one, mwah ππ
π¦ 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