c++ hashset的用法_c++ 使用unordered_set实现hashset

使用unordered_set库来构造hashset

unordered_set 官方文档介绍

Unordered sets are containers that store unique elements in no particular order, and which allow for fast retrieval of individual elements based on their value.

In an unordered_set, the value of an element is at the same time its key, that identifies it uniquely. Keys are immutable, therefore, the elements in an unordered_set cannot be modified once in the container - they can be inserted and removed, though.

Internally, the elements in the unordered_set are not sorted in any particular order, but organized into buckets depending on their hash values to allow for fast access to individual elements directly by their values (with a constant average time complexity on average).

unordered_set containers are faster than set containers to access individual elements by their key, although they are generally less efficient for range iteration through a subset of their elements.

Iterators in the container are at least forward iterators.

简单来说,unordered_key非常的高效,使用值本身作为键值

Example

#include

#include

using namespace std;

int main() {

// 1. initialize a hash set

unordered_set hashset;

// 2. insert a new key

hashset.insert(1);

hashset.insert(2);

hashset.insert(3);

// 3. delete a key

hashset.erase(2);

// 4. check if the key is in the hash set

if (hashset.count(2) <= 0) {

cout << "Key 2 is not in the hash set." << endl;

}

// 5. get the size of the hash set

cout << "The size of the hash set is " << hashset.size() << endl;

// 6. iterate the hash set

for (auto it = hashset.begin(); it != hashset.end(); it++) {

cout << (*it) << " ";

}

cout << "is in the hash set." << endl;

// 7. clear the hash set

hashset.clear();

// 8. check if the hash set is empty

if (hashset.empty()) {

cout << "hash set is empty now!" << endl;

}

return 0;

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值