Re: Initializing a map...
barcaroller wrote:
Is there a way in C++ to initialize an STL map in one statement (the way
arrays can be initialized in C)?
For example, instead of using:
map<type1,type2> mymap;
mymap[key1] = value1;
mymap[key2] = value2;
I would like to use something like:
// wrong syntax!
map<type1,type2> mymap = { (key1, value1), (key2, value2) };
There's no special syntax for maps. You do have a few options, though.
One is to initialize an array with the nicer syntax, then initialize
the map from the array.
typedef std::map<type1, type2> map_type;
typedef map_type::value_type pair_type;
template<typename T, std::size_t z>
std::size_t size(T const (&a)[z]) {
return z;
}
int main() {
pair_type initializers[] =
{ pair_type(key1, value1), pair_type(key2, value2) };
map_type m(initializers, initializers + size(initializers));
}
Another option is to create the map within a function, then return it by
value.
map_type create_map() {
map_type result;
result.insert(pair_type(key1, value1));
result.insert(pair_type(key2, value2));
return result;
}
int main() {
map_type map = create_map();
}
A third option is to let the map start out empty, then use a function to
populate it.
void populate(map_type& m) {
m.insert(pair_type(key1, value1));
m.insert(pair_type(key2, value2));
}
int main() {
map_type m;
populate(m);
}