I have an std:map defined as follows:
std:map<std::string country, std::vector<SomeClass> events>;
Holds some events that will happen in some countries in the world.
I want my main function to create this map given a name to the key but without inserting a value. Let's say that the key is the name of a country. I want to create the "position" "USA" without inserting an event that will happen in the future.
My event() function will enter a new even without checking if the key is valid
Is this possible? Somehow to enter a value_pair with "empty" value?
UPDATE: No boost ...
Will inserting an empty vector do the trick?...
events.insert(std::make_pair("USA", std::vector<SomeClass>()));
You could then add actual events without checking of existence of map's value:
void event(const std::string& country, const SomeClass& data) {
events[country].push_back(data);
}
I'm not sure whether this is what you're looking for, since the notion of 'creating "position" "USA"' looks ambiguous. (And earlier answers seem to pick different interpretation of it).
EDIT: As commenters pointed out, inserting the empty vector is not even necessary, since map values are automatically created (using default initializer) & inserted when one uses the [] operator. Hence you you can just do events["USA"].push_back(data) directly.
I think what you're looking for is std::multimap. This allows more than one value per key:
typedef std::multimap<std::string, SomeClass> EventMap;
typedef EventMap::value_type EntryType; // std::pair<..>
std::multimap<std::string, SomeClass> events;
// Add value
events.insert(std::make_pair("Norway", SomeClass(...)));
If you really need to be able mark a country as valid by inserting an empty placeholder I think that using a separate std::set probably would be a better solution. If you really want to do this, boost::optional or shared_ptr as mentioned by sehe is another solution.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With