Setting all values ​​to std :: map

How to set all values ​​in std::map to the same value without using a loop repeating each value?

+6
c ++ stl
source share
3 answers

C ++ has a fill method from <algorithm> , but this does not work for maps. In fact, support for associative container algorithms is usually small.

As a result, you will need to use interation or write the corresponding functor that will be used with for_each (but I think this is an extra 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)); 
+13
source share

I ran into the same problem, but found that the range returned by boost :: adapters :: values ​​is mutable, so it can be used with regular algorithms like std :: fill.

 #include <boost/range/adaptor/map.hpp> auto my_values = boost::adaptors::values(my_map); std::fill(my_values.begin(), my_values.end(), 123); 
+3
source share

The boost :: assign library has all sorts of neat things to help initialize the contents of the container. I thought this could be used to avoid explicit iteration through the map. Unfortunately, curious animal cards are hard to initialize, because the keys must be unique. The bottom line is that a simple looping cycle is probably the best way to initialize a map. It may not be very elegant, but it does its job and is immediately understandable to anyone familiar with the STL.

 map <int,string> myMap; for( int k=0;k<1000;k++) myMap.insert(pair<int,string>(k,string(""))); 

The rest of this post describes the journey I took to reach the above conclusion.

The boost :: assign function makes it easy to assign a small number of values ​​to a map.

 map<string,int> m; insert( m )( "Bar", 1 )( "Foo", 2 ); 

or

  map<int,int> next = map_list_of(1,2)(2,3)(3,4)(4,5)(5,6); 

In your case, when you want to initialize the entire map with the same value, there are repeat and repeat_fun utilities.
Something like this should work with multimap (an untested piece of code)

 pair<int,string> init( 0,string("")); multimap <int,string> myMap = repeat(1000,init); 

As Conrad Rudolph pointed out, you cannot initialize a map with the same exact value, because the keys must be unique.

It makes life a lot more complicated (fun?). Something like this is possible:

 map <int,string> myMap; struct nextkey { int start; nextkey( s ) : start( s ) {} pair<int,string> operator () () { return pair<int,string>(start++,string("")); } }; myMap = repeat_fun(1000,nextkey(0)); 

Now it gets so complicated, now I think simple iteration is the way to go

 map <int,string> myMap; for( int k=0;k<1000;k++) myMap.insert(pair<int,string>(k,string(""))); 
+2
source share

All Articles