【问题标题】:Java HashSet equivalent in C++C++ 中的 Java HashSet 等价物
【发布时间】:2014-08-29 22:02:57
【问题描述】:

我很好奇 C++ 中是否有类似于 Java HashSet 的东西? IE。一个快速查看的数据结构,因为我只会在它上面运行.contains(e)。同样,如果您能告诉我如何对您提出的任何数据结构执行.contains(),我将不胜感激。哦,请不要只看 c++ 文档,因为我已经这样做了,发现它们很麻烦。

【问题讨论】:

  • std::unordered_set 是最接近的

标签: c++ data-structures stl lookup


【解决方案1】:

您可以使用 std::unordered_set<>(标准 § 23.5.6),它的 find 方法(进行查找)作为 O(1) 的平均复杂度:

#include <iostream>
#include <unordered_set>

int main()
{  
    std::unordered_set<int> example = {1, 2, 3, 4};

    auto search = example.find(2);
    if(search != example.end()) {
        std::cout << "Found " << (*search) << '\n';
    }
    else {
        std::cout << "Not found\n";
    }
}

编辑:

根据@Drew Dormann 的建议,您也可以使用count,它的平均复杂度也为 O(1):

#include <iostream>
#include <unordered_set>

int main()
{  
    std::unordered_set<int> example = {1, 2, 3, 4};

    if(example.count(2)) {
        std::cout << "Found\n";
    }
    else {
        std::cout << "Not found\n";
    }
}

【讨论】:

  • 我推荐 count() 来模拟 contains()。那 2 行 if 变成了简单的if(example.count(2))
  • 该函数被命名为count()以与多集一致,但对于unordered_set,它只会返回1 (true)0 (false)
猜你喜欢
  • 2018-05-17
  • 2011-07-21
  • 1970-01-01
  • 2010-11-19
  • 2010-10-24
  • 1970-01-01
  • 2014-11-22
  • 1970-01-01
  • 2011-04-25
相关资源
最近更新 更多