Reputation: 119
I am doing a practice in C++ based on data structures.
My class contains an attribute like this map<int, list <Route *>>
. My question is, what happens when I add a key to the map. Must I initialize the list or not? My wish is to have an empty file in the description of that key.
Something like this is what I thought:
map<int, list<Route* > >::iterator it= _mapRoutesAirline.find(IDAirline);
if(it == _mapRoutesAirline.end())
_mapRoutesAirline[IDAirline] = list<Route*>();
Upvotes: 2
Views: 145
Reputation: 376
You can create an empty list when you define a new key, no need to define the data type of the list.
_mapRoutesAirline[IDAirline] = {};
Also, you don't need to define an iterator just to find and insert element It can be done in this way
if(_mapRoutesAirline.find(IDAirline) == _mapRoutesAirline.end()){
_mapRoutesAirline[IDAirline] = {};
}
Upvotes: 1
Reputation: 2048
Yes, you can simply assign to the map element (syntax assuming C++11 or above):
_mapRoutesAirline[IDAirline] = {};
Note that in many use cases you don't have to assign an empty list, because any attempt to access a key that isn't present in the map yet will automatically create a default constructed list for that key, which is an empty list. This means that, for example, _mapRoutesAirline[42]
would return an empty list if you hadn't assigned anything to the _mapRoutesAirline[42]
yet.
Upvotes: 2
Reputation: 7374
Yes you can add an empty list to the map as value e.g.:
if(it == _mapRoutesAirline.end())
_mapRoutesAirline.insert(std::make_pair(IDAirline, list<Route*>{}));
Upvotes: 1