C ++中的Java HashSet等效项 [英] Java HashSet equivalent in c++

查看:77
本文介绍了C ++中的Java HashSet等效项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很好奇,是否有类似于c ++中Java哈希集的东西.即具有快速外观的数据结构,因为我将仅在其上运行.contains(e).同样,如果您可以启发我如何对所建议的任何数据结构执行.contains(),我将不胜感激.哦,请不要发表我已经做过的事情,而只是看一下c ++文档,发现它们很麻烦.

I was curious if there was something akin the the Java hashset in c++. I.e a data structure with fast look, as I will only be running .contains(e) on it. Likewise, if you could enlighten me on how to do a .contains() on whatever data structure you propose, I would be very appreciative. O, please do not post just look at the c++ docs as I have already done so and find them burdensome.

推荐答案

您可以使用std::unordered_set<>(标准§23.5.6),其

You can use std::unordered_set<> (standard § 23.5.6), its find method (to do a lookup) as an average complexity of 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):

As suggested by @Drew Dormann, you can alternatively use count, which also has a average complexity of 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";
    }
}

这篇关于C ++中的Java HashSet等效项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆