C ++ unordered_map 如何区分空单元格与0(C++ unordered_map how to distinguish null cell from 0)
假设我有一个unordered_map<string, int> H
假设H中没有元素“house”,所以cout<<H["house"]; 会打印0。
但是假设我需要指定H["house"] = 0 。
如何区分不存在的元素和0的元素?
//example of what I want: if(!H["house"]){ cout<<"DOES NOT EXIST YET\n"; H["house"] = 0; } if(H["house"]){ cout<<"IT EXISTS NOW\n"; }Suppose I have an unordered_map<string, int> H.
Let's say there is no element "house" in H, so cout<<H["house"]; would print 0.
But suppose I need to assign H["house"] = 0.
How would I distinguish an element that doesn't exist from one that is 0?
//example of what I want: if(!H["house"]){ cout<<"DOES NOT EXIST YET\n"; H["house"] = 0; } if(H["house"]){ cout<<"IT EXISTS NOW\n"; }最满意答案
最短的测试:
if (H.count("house")) { // "house" exists } else { // "house" does not exist in H }The shortest test:
if (H.count("house")) { // "house" exists } else { // "house" does not exist in H }更多推荐
发布评论