Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //
- // Заголовочный файл dict.h
- //
- #pragma once
- #include <string>
- /**
- * Dictionary that maps strings to strings.
- */
- class Dictionary {
- public:
- Dictionary();
- int hash(const std::string &key);
- /// Set value for the key.
- /// Replace old value with the new one if the key already exists.
- void set(const std::string &key, const std::string &value);
- /// Get value for the key.
- /// Returns empty string if there is no such key.
- std::string get(const std::string &key);
- /// Get number of items (keys) in the dictionary.
- int size() const;
- private:
- int count;
- int N = 10;
- std::string* table;
- };
- //
- // Файл исходного кода dict.cpp
- //
- #include "dict.h"
- // Methods to implement
- Dictionary::Dictionary() {
- table = new std::string[N];
- for (int i = 0; i < N; i++) {
- table[i] = "";
- }
- }
- int Dictionary::hash(const std::string &word) {
- int hash = 0;
- int i = 0;
- while (i < word.length()) {
- hash += word[i];
- i++;
- }
- hash = (int)hash % N;
- return hash;
- }
- void Dictionary::set(const std::string &key, const std::string &word) {
- table[hash(key)] = word;
- }
- std::string Dictionary::get(const std::string &key) {
- if (table[hash(key)] != "") return table[hash(key)];
- else return NULL;
- }
- int Dictionary::size() const {
- int count = 0;
- for (int i = 0; i < N; i++) {
- if (table[i] != "") count++;
- }
- // Return size of the dictionary, i.e. number of key-value pairs.
- return count;
- }
- //
- // Мэйн
- //
- #include <stdio.h>
- #include "dict.h"
- void main() {
- Dictionary dict;
- int size = dict.size();
- const std::string one = "asda";
- const std::string two = "a";
- dict.set(one, two);
- getchar();
- getchar();
- }
Advertisement