Java HashSet等价于c ++ [英] Java HashSet equiv in c++

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

问题描述

我好奇,如果有一些类似于cava中的Java哈希表。即,一个具有快速查看的数据结构,因为我将只对其运行.contains(e)。同样,如果你可以启发我如何做一个.contains()在你提出的任何数据结构,我会非常感谢。 O,请不要张贴只看看c ++ docs,因为我已经这样做,并发现他们负担。

解决方案

您可以使用 std :: unordered_set<> §23.5.6),其 找到 方法(执行查找)作为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)<< '\\\
';
}
else {
std :: cout< 未找到\\\
;
}
}

EDIT: p>

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

  #include  #include< unordered_set> 

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

if(example.count(2)){
std :: cout< Found\\\
;
}
else {
std :: cout< 未找到\\\
;
}
}


I as 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.

解决方案

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";
    }
}

EDIT:

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";
    }
}

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

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