Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

std::map prepare but do not insert

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 ...

like image 732
cateof Avatar asked Feb 10 '26 09:02

cateof


2 Answers

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.

like image 195
Xion Avatar answered Feb 14 '26 00:02

Xion


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.

like image 37
larsmoa Avatar answered Feb 14 '26 01:02

larsmoa