std::map::value_comp(3)

πŸ“¦ version 2024.07.05, in nixpkgs unstable, opensuse-leap 16.0

✨ 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