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?
- 1What have you tried? What about your attempt(s) do you feel are not succinct enough?Some programmer dude– Some programmer dude2020-01-09 07:40:26 +00:00CommentedJan 9, 2020 at 7:40
- 1@Someprogrammerdude: Best solution I have so far is
.equal_rangeexample 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.Andrew Tomazos– Andrew Tomazos2020-01-09 07:47:10 +00:00CommentedJan 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_eachmember function might have been nice. But is it a common enough use-case that it should be added to the standard?Some programmer dude– Some programmer dude2020-01-09 07:57:27 +00:00CommentedJan 9, 2020 at 7:57 - 2@Kerndog73: I don't think your
for_eachworks becausemutateoperates onVnotstd::pair<K,V>.mutateis just a proxy for some code that does something with aV.Andrew Tomazos– Andrew Tomazos2020-01-09 08:03:46 +00:00CommentedJan 9, 2020 at 8:03 - 2In the linked example you could subsume the call to
equal_rangeinto theinitexpression of theforloop 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.G.M.– G.M.2020-01-09 08:04:15 +00:00CommentedJan 9, 2020 at 8:04
1 Answer1
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
172k23 gold badges402 silver badges482 bronze badges
Sign up to request clarification or add additional context in comments.
Comments
Explore related questions
See similar questions with these tags.