Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <fstream>
- #include <iostream>
- #include <string>
- #include <vector>
- #include <math.h>
- #include <list>
- #include <algorithm>
- using namespace std;
- template<typename T1, typename T2>
- class Map {
- private:
- const int PRIME_SIZE = 200003;
- vector<list<pair<T1, T2>>>* hashTable;
- int hash(T1 key) const {
- unsigned long hash = 5381;
- for (auto i : key)
- hash = ((hash << 5) + hash) + i;
- return hash % PRIME_SIZE;
- }
- public:
- Map() {
- this->hashTable = new vector<list<pair<T1, T2>>>(PRIME_SIZE);
- }
- ~Map() {
- delete this->hashTable;
- }
- void insert(pair<T1, T2> pair) {
- auto collision_list = &hashTable->at(hash(pair.first));
- auto key = pair.first;
- auto find_iter = find_if(collision_list->begin(), collision_list->end(), [key](const std::pair<T1, T2>& p) {
- return key == p.first;
- });
- if (find_iter == collision_list->end())
- collision_list->push_back(pair);
- else
- find_iter->second = pair.second;
- }
- void erase(T1 key) {
- auto collision_list = &hashTable->at(hash(key));
- auto find_iter = find_if(collision_list->begin(), collision_list->end(), [key](const pair<T1, T2>& p) {
- return key == p.first;
- });
- if (find_iter != collision_list->end())
- collision_list->erase(find_iter);
- }
- auto find(T1 key) const {
- int index = hash(key);
- return find_if(hashTable->at(index).begin(), hashTable->at(index).end(), [key](const pair<T1, T2>& p) {
- return key == p.first;
- });
- }
- T2 get(T1 key) {
- auto collision_list = &hashTable->at(hash(key));
- auto find_iter = find_if(collision_list->begin(), collision_list->end(), [key](const std::pair<T1, T2>& p) {
- return key == p.first;
- });
- if (find_iter != collision_list->end())
- return find_iter->second;
- else
- return T2();
- }
- };
- int main() {
- ifstream ist("map.in");
- ofstream ost("map.out");
- Map<string, string> newMap;
- string com;
- string key;
- while (ist >> com >> key) {
- if (com == "put") {
- string value;
- ist >> value;
- newMap.insert(make_pair(key, value));
- }
- else if (com == "delete")
- newMap.erase(key);
- else if (com == "get") {
- string find = newMap.get(key);
- ost << (find == "" ? "none" : find) << endl;
- }
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement