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