find() 的替代方法,用于确定 unordered_set 是否包含键

Alternative to find() for determining whether an unordered_set contains a key

假设我有一个 unordered_set<int> S,我想检查它是否包含某个 int x

有没有办法让我写出类似 if(S.contains(x)){ /* code */ } 的东西,并且像 if(S.find(x) != S.end()){ /* code */ } 一样工作?

它可以是一个宏或任何东西,但我只是觉得写这样一个简单的查找方法很丑而且不必要地长。

而不是使用 std::unordered_setfind() 成员函数来确定给定键 x 是否存在,如:

if (S.find(x) != S.end()) { /* code */ }

你可以简单地使用count()成员函数:

if (S.count(x)) { /* code */ }

std::unordered_set 不允许重复,因此 count() 将 return 01


unordered_set::count() 成员函数不应该比 unordered_set::find() 效率低,因为一旦找到一个元素,就可以停止遍历元素以找出所请求键的计数,因为不能重复。

我认为你需要 if(S.count(x)){//do something}。 根据 cplusplus.com,count 函数在容器中搜索值为 k 的元素,returns 找到的元素数。因为 unordered_set 容器不允许重复值,这意味着如果容器中存在具有该值的元素,函数实际上 returns 1,否则为零。