2

Suppose I have some function:

void mutate(V& v);

that reads/writes v - and I want to write a function:

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

that applies mutate to all values of m that have key k.

What's the most succinct way to implement mutate_map_values in C++20?

7
  • 1
    What have you tried? What about your attempt(s) do you feel are not succinct enough? Commented Jan 9, 2020 at 7:40
  • 1
    @Someprogrammerdude: Best solution I have so far is .equal_range example here: en.cppreference.com/w/cpp/container/multimap/equal_range . I'd like to know if there is a shorter way I am missing before I propose one to the C++ standards commitee. Commented Jan 9, 2020 at 7:47
  • Well that currently seems like the best way to find all elements of a specific key. It's not very succinct to iterate over elements of the same key using it though. Some kind of for_each member function might have been nice. But is it a common enough use-case that it should be added to the standard? Commented Jan 9, 2020 at 7:57
  • 2
    @Kerndog73: I don't think your for_each works because mutate operates on V not std::pair<K,V>. mutate is just a proxy for some code that does something with a V. Commented Jan 9, 2020 at 8:03
  • 2
    In the linked example you could subsume the call to equal_range into the init expression of the for loop and use a structured binding such as for (auto [i, e] = m.equal_range(key); i != e; ++i). Other than that it's difficult to judge without seeing an example of the code you would like to be able to write. Commented Jan 9, 2020 at 8:04

1 Answer 1

5

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 already returns. Combining the two, we may write the desired function as follows in 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);
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Draft saved
Draft discarded

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.