Your question is somewhat unclear. You cannot insert a key without inserting a value as well. If this is really your intent, the answer is: No.
For your purpose I see no reason why you could not insert an empty vector instead (as others have pointed out). For actually doing this, you can do the insertion on initialisation of the map:
#include <string>
#include <map>
#include <initializer_list>
using namespace std;
class SomeClass { int x; };
int main() {
SomeClass e1, e2, e3;
map< string, vector<SomeClass> > events = // using initializer_list from c++0x
{
{"USA",{e1,e2}}, {"CANADA",{ /* no events */ }, {"MEXICO",{e2,e3}}
};
// or later ...
events["CUBA"] = {};
events["RUSSIA"] = {e1,e2,e3};
}
Alternatively, you could return a default value if the key is not present when you ask for it, i.e. lazy initialization.
The default behavior of the map
is to add a new entry to the map using the default constructor of the value type whenever the requested key is missing. Which produces an empty vector<SomeClass>
in this case.
Therefore, I don't see what's wrong with this:
events["key that is missing beforehand"].push_back(e1);
If you actually want to avoid adding new entries to the map, you need to wrap your requests with something like:
string key = "USA";
vector<SomeClass> localEvents; // default, empty vector
// using the auto type from c++0x
auto ev = events.find(key);
if (ev == events.end()) // not found
//events[key] = {}; // don't add the key to the map
;
else // get the corresponding vector
localEvents = (*ev).second;
For this, you might also want to consider this related question: std::map default value
(The examples would work perfectly even without the c++0x
features.)