Read/write 在 C++20 中具有给定键的 std::multimap 的所有值?

Read/write all values of a std::multimap with a given key in C++20?

假设我有一些功能:

void mutate(V& v);

那个 reads/writes v - 我想写一个函数:

void mutate_map_values(std::multimap<K,V>& m, K k);

mutate 应用到具有键 k.

m 的所有值

在 C++20 中实现 mutate_map_values 的最简洁方法是什么?

std::ranges::subrange is a utility class that's constructible from anything that is like a pair of iterators. Which fits with what std::multimap::equal_range 已经 returns。结合两者,我们可以在C++20中编写如下所需的函数:

#include <ranges>

void mutate_map_values(std::multimap<K,V>& m, K k) {
    using namespace std::ranges;
    for (auto& [_, v] : subrange(m.equal_range(k))) {
        mutate(v);
    }
}