随机获取元素的hash map

256 篇文章 3 订阅
149 篇文章 2 订阅
#include <time.h>
#include <iostream>
#include <vector>
#include <unordered_map>
#include <random>
std::default_random_engine G_SEED(time(NULL));  
class RandomHashSet {
public:
    RandomHashSet() = default;
    ~RandomHashSet() = default;
public:
    inline void set_capacity(size_t cap) {
        max_capacity = cap;
    }
    bool insert(const std::string &str) {
        if (array_.size() >= max_capacity) {
            std::cerr << "up to max capacity = " << max_capacity << std::endl;
            return false;
        }
        if (val_index_map_.find(str) != end(val_index_map_)) {
            return false;
        }
        array_.emplace_back(str);
        val_index_map_[str] = array_.size() - 1;
        return true;
    }
    bool remove(const std::string &str) {
        auto it = val_index_map_.find(str);
        if (end(val_index_map_) == it) {
            return false;
        }
        int index = it->second;
        auto &last_str = *(end(array_) - 1);
        val_index_map_[last_str] = index;
        std::swap(array_[index], last_str);
        array_.pop_back();
        val_index_map_.erase(it);
        return true;
    }
    bool get_random(std::string &str) {
        if (array_.empty()) {
            return false;
        }
        int limit = array_.size() - 1;
        std::uniform_int_distribution<int>engine(0, limit);
        int index = engine(G_SEED);
        str = array_[index];
        return true;
    }
private:
    size_t max_capacity = 1024;
private:
    std::unordered_map<std::string, int>val_index_map_;
    std::vector<std::string>array_;
};
int main() {
    RandomHashSet RS;
    std::string str = "ABC";
    RS.insert(str);
    str = "ABCD";
    RS.insert(str);
    for (int i = 0;i < 10;i++) {
        str.clear();
        RS.get_random(str);
        std::cout << "i = " << i << " str = " <<str << std::endl;
    }
    std::cout << RS.remove(str) << std::endl;
    std::cout << RS.remove(str) << std::endl;

    return 0;
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值