2

Suppose I have some function:

void mutate(V& v);

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

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

that appliesmutate to all values ofm that have keyk.

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

askedJan 9, 2020 at 7:35
Andrew Tomazos's user avatar
7
  • 1
    What have you tried? What about your attempt(s) do you feel are not succinct enough?CommentedJan 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.CommentedJan 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 offor_each member function might have been nice. But is it a common enough use-case that it should be added to the standard?CommentedJan 9, 2020 at 7:57
  • 2
    @Kerndog73: I don't think yourfor_each works becausemutate operates onV notstd::pair<K,V>.mutate is just a proxy for some code that does something with aV.CommentedJan 9, 2020 at 8:03
  • 2
    In the linked example you could subsume the call toequal_range into theinit expression of thefor loop and use a structured binding such asfor (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 wouldlike to be able to write.CommentedJan 9, 2020 at 8:04

1 Answer1

5

std::ranges::subrange is a utility class that's constructible from anything that is like a pair of iterators. Which fits with whatstd::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);    }}
answeredJan 9, 2020 at 8:16
StoryTeller - Unslander Monica's user avatar
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

Sign up orlog in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

By clicking “Post Your Answer”, you agree to ourterms of service and acknowledge you have read ourprivacy 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.