Will Will - 3 years ago 96
C++ Question

Setting all values in a std::map

How to set all the values in a

std::map
to the same value, without using a loop iterating over each value?

Answer Source

C++ has the fill method from <algorithm> but this doesn't work for maps. In fact, algorithm support for associative containers is generally not good.

As a result, you'll have to use an interation or write an appropriate functor to be used with for_each (but I consider this to be unnecessary overhead):

template <typename TKey, typename TValue>
struct resetter : public std::unary_function<std::pair<TKey, TValue> > {
    TValue const value;

    public resetter(value const& v) : value(v) { }

    public void operator ()(std::pair<TKey, TValue>& v) {
        v.second = value;
    }
};

for_each(map.begin(), map.end(), resetter<Key, Value>(value));
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download