How to set all the values in a std::map to the same value, without using a loop iterating over each value?
How to set all the values in a std::map to the same value, without
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
Using a loop is by far the simplest method. In fact, it’s a one-liner:[C++17]
Unfortunately C++ algorithm support for associative containers isn’t great pre-C++20. As a consequence, we can’t directly use
std::fill.To use them anyway (pre-C++20), we need to write adapters — in the case of
std::fill, an iterator adapter. Here’s a minimally viable (but not really conforming) implementation to illustrate how much effort this is. I do not advise using it as-is. Use a library (such as Boost.Iterator) for a more general, production-strength implementation.With this, we can use
std::fill: