Gistrec

mpiaa_hw2_v1

Oct 26th, 2017
283
0
Never
1
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.70 KB | None | 0 0
  1. //
  2. // Заголовочный файл dict.h
  3. //
  4. #pragma once
  5.  
  6. #include <string>
  7.  
  8. /**
  9. * Dictionary that maps strings to strings.
  10. */
  11. class Dictionary {
  12. public:
  13.     Dictionary();
  14.  
  15.     int hash(const std::string &key);
  16.     /// Set value for the key.
  17.     /// Replace old value with the new one if the key already exists.
  18.     void set(const std::string &key, const std::string &value);
  19.  
  20.     /// Get value for the key.
  21.     /// Returns empty string if there is no such key.
  22.     std::string get(const std::string &key);
  23.  
  24.     /// Get number of items (keys) in the dictionary.
  25.     int size() const;
  26.    
  27. private:
  28.     int count;
  29.     int N = 10;
  30.     std::string* table;
  31. };
  32.  
  33. //
  34. // Файл исходного кода dict.cpp
  35. //
  36. #include "dict.h"
  37.  
  38. // Methods to implement
  39.  
  40. Dictionary::Dictionary() {
  41.     table = new std::string[N];
  42.     for (int i = 0; i < N; i++) {
  43.         table[i] = "";
  44.     }
  45. }
  46.  
  47. int Dictionary::hash(const std::string &word) {
  48.     int hash = 0;
  49.     int i = 0;
  50.     while (i < word.length()) {
  51.         hash += word[i];
  52.         i++;
  53.     }
  54.     hash = (int)hash % N;
  55.     return hash;
  56. }
  57.  
  58. void Dictionary::set(const std::string &key, const std::string &word) {
  59.     table[hash(key)] = word;
  60. }
  61.  
  62. std::string Dictionary::get(const std::string &key) {
  63.     if (table[hash(key)] != "") return table[hash(key)];
  64.     else return NULL;
  65. }
  66.  
  67. int Dictionary::size() const {
  68.     int count = 0;
  69.     for (int i = 0; i < N; i++) {
  70.         if (table[i] != "") count++;
  71.     }
  72.     // Return size of the dictionary, i.e. number of key-value pairs.
  73.     return count;
  74. }
  75.  
  76. //
  77. // Мэйн
  78. //
  79.  
  80. #include <stdio.h>
  81. #include "dict.h"
  82.  
  83. void main() {
  84.     Dictionary dict;
  85.     int size = dict.size();
  86.     const std::string one = "asda";
  87.     const std::string two = "a";
  88.     dict.set(one, two);
  89.     getchar();
  90.     getchar();
  91. }
Advertisement
Comments
  • User was banned
Add Comment
Please, Sign In to add comment