Adrian
Adrian

Reputation: 2365

How do I access (check) the element of a std::unordered_map without inserting into it?

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

Answers (2)

Jon
Jon

Reputation: 437336

Yes, you have to check by using find:

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

Upvotes: 3

Dave S
Dave S

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

Related Questions