Question

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?

Was it helpful?

Solution

Yes, you have to check by using find:

if (umap.find("Randy") == umap.end()) // does not exist

OTHER TIPS

Other than find() or count(), the other alternative is the at() method, which throws an exception if it's not present.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top