Reputation: 2365
Accessing elements of a std::unordered_map using the [ ] operator inserts new elements:
std::unordered_map<std::string, uint32_t> umap = {
{"Thomas", 1},
{"Frank", 5},
{"Lisa", 7}
};
// umap.size() is 3
uint32_t id = umap["Lisa"];
// umap.size() is 3
id = umap["Randy"]; // key "Randy" doesn't exist
// umap.size() is 4
I had naively assumed the [ ] operator would behave read-only without right-hand assignment. Do I have to check via count()
or find()
whether a key exists, prior to accessing it, or is there an alternative?
Upvotes: 1
Views: 4377
Reputation: 437336
Yes, you have to check by using find
:
if (umap.find("Randy") == umap.end()) // does not exist
Upvotes: 3
Reputation: 21058
Other than find()
or count()
, the other alternative is the at()
method, which throws an exception if it's not present.
Upvotes: 1