reading object from const unordered_map

后端 未结 2 1265
南笙
南笙 2021-01-07 17:21

Why am I not allowed to read an object from a constant unordered_map?

const unordered_map z;
int val = z[5]; // compile error
2条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-07 18:08

    As Jonathan already said, the operator[] method is non-const because it might add a default value when the item being looked up is not found.

    On the other hand, as highlighted from Benjamin in a comment, the at() method is available for const as well.

    const unordered_map z;
    int val = z.at(5); // Success!
    

    The downside is that when the value being looked up is not in the map, a std::out_of_range exception is raised, so it has to be managed.

提交回复
热议问题