0
点赞
收藏
分享

微信扫一扫

hash.count 与 hash[]的区别,什么时候用.count,什么时候用hash[]?

幸福的无所谓 2022-03-13 阅读 94
class Solution 
{ 
public:       
    vector<int> twoSum(vector<int>& nums, int target) 
    {   /** 由于unorder_map速度要比map快所以选择无序哈希表 */                   
        vector<int> res;         
        unordered_map<int, int> hash;
        for(int i=0; i < nums.size();++i)
        {             
            int another = target - nums[i];             
            if(hash.count(another))
            {                   
                res = vector<int>({hash[another], i});                 
                return res;             
            }             
            hash[nums[i]] = i;         
        }         
        return res;     
    } 
};

这两种写法的含义是不一样的:

  • if (hash.count(key)) 是判断hash表中是否存在关键字key
  • if (hash[key]) 是判断key对应的value值是否是真,如果keyhash表中不存在,则会先为其创建默认值,比如int的默认值是0vector<int>的默认值是vector<int>()

C++中,如果想往哈希表中插入一对(key, value),一般写hash[key] = value
如果想查找一个key是否存在,一般有两种写法:

  • if (hash.find(key) != hash.end())
  • if (hash.count(key) != 0)
    第二种写法短一些,所以用得比较多。
举报

相关推荐

0 条评论