Beispiellösung

Content

#ifndef HASH_HPP
#define HASH_HPP

#include <cassert>
#include <cstdlib>
#include <functional>
#include <memory>
#include <utility>

template<typename Key, typename Value>
class Hash {
   public:
      using Object = std::pair<const Key, Value>;
   private:
      struct Node;
      using NodePtr = std::shared_ptr<Node>;
      struct Node {
	 Node(Object object) : object(std::move(object)) {
	 }
	 Node(Object object, NodePtr next) :
	    object(std::move(object)), next(next) {
	 }
	 Object object;
	 NodePtr next;
      };
      const std::size_t dim;
      std::shared_ptr<NodePtr[]> bucket;
      std::hash<Key> hash;
      std::size_t count; /* number of objects */
   public:

      class Iterator {
	 public:
	    friend Hash;
	    Iterator() : dim(0), index(0) {
	    }
	    Iterator(Hash& hash) :
		  dim(hash.dim), bucket(hash.bucket), index(0) {
	       advance();
	    }
	    Iterator(Hash& hash, std::size_t index, NodePtr prev, NodePtr node) :
		  dim(hash.dim), bucket(hash.bucket), index(index),
		  prev(prev), node(node) {
	       assert(node && index < dim);
	    }
	    Object& operator*() {
	       return node.lock()->object;
	    }
	    const Object& operator*() const {
	       return node.lock()->object;
	    }
	    Object* operator->() {
	       return &node.lock()->object;
	    }
	    Iterator& operator++() {
	       advance();
	       return *this;
	    }
	    bool operator==(const Iterator& other) {
	       bool end1 = index >= dim;
	       bool end2 = other.index >= other.dim;
	       if (end1 && end2) return true;
	       if (end1 || end2) return false;
	       return
		  bucket.lock() == other.bucket.lock() &&
		  index == other.index &&
		  node.lock() == other.node.lock();
	    }
	    bool operator!=(const Iterator& other) {
	       return !(*this == other);
	    }
	 private:
	    void advance() {
	       /* move to next object */
	       auto b = bucket.lock();
	       if (b) {
		  auto n = node.lock();
		  if (n) {
		     node = n->next;
		     n = node.lock();
		     if (!n) ++index;
		  }
		  if (!n) {
		     while (index < dim && !b[index]) {
			++index;
		     }
		     if (index < dim) {
			node = b[index];
		     }
		  }
	       } else {
		  node = NodePtr(); index = dim;
	       }
	    }
	    std::size_t dim;
	    std::weak_ptr<NodePtr[]> bucket;
	    std::size_t index; /* current location in bucket table */
	    std::weak_ptr<Node> prev; /* previous object, if any in the same list */
	    std::weak_ptr<Node> node; /* current object at bucket[index] */
      };

      Hash(std::size_t dim) :
	 // dim(dim), bucket(std::make_shared<NodePtr[]>(dim)) {
	 dim(dim), bucket(new NodePtr[dim]), count(0) {
      }
      std::pair<Iterator, bool> insert(Object object) {
	 auto index = hash(object.first) % dim;
	 auto ptr = bucket[index];
	 NodePtr prev;
	 while (ptr && ptr->object.first != object.first) {
	    prev = ptr; ptr = ptr->next;
	 }
	 bool inserted;
	 if (ptr) {
	    inserted = false;
	 } else {
	    ptr = std::make_shared<Node>(std::move(object), bucket[index]);
	    bucket[index] = ptr;
	    prev = nullptr;
	    inserted = true;
	    ++count;
	 }
	 return std::make_pair(Iterator(*this, index, prev, ptr), inserted);
      }
      Iterator find(Key key) {
	 auto index = hash(key) % dim;
	 auto ptr = bucket[index];
	 NodePtr prev;
	 while (ptr && ptr->object.first != key) {
	    prev = ptr; ptr = ptr->next;
	 }
	 if (ptr) {
	    return Iterator(*this, index, prev, ptr);
	 } else {
	    return Iterator();
	 }
      }
      void erase(Iterator it) {
	 if (it.bucket.lock() == bucket && it.index < dim) {
	    auto node = it.node.lock();
	    auto prev = it.prev.lock();
	    if (node) {
	       if (prev) {
		  prev->next = node->next;
	       } else {
		  bucket[it.index] = node->next;
	       }
	       --count;
	    }
	 }
      }
      template<typename F>
      void for_each(F&& f) {
	 for (std::size_t index = 0; index < dim; ++index) {
	    auto ptr = bucket[index];
	    while (ptr) {
	       f(ptr->object);
	       ptr = ptr->next;
	    }
	 }
      }
      Iterator begin() {
	 return Iterator(*this);
      }
      Iterator end() {
	 return Iterator();
      }
      std::size_t size() const {
	 return count;
      }
};

#endif
#include <fstream>
#include <iostream>
#include <string>
#include "Hash.hpp"

int main() {
   Hash<std::string, unsigned int> hash(32);
   std::string town; unsigned int population;
   std::ifstream cities("cities");
   while (cities >> town && cities >> population) {
      bool ok;
      std::tie(std::ignore, ok) = hash.insert(std::make_pair(town, population));
      if (!ok) {
	 std::cerr << "insertion of " << town << " failed." << std::endl;
      }
   }
   std::cout << hash.size() << " objects loaded from 'cities'." << std::endl;
   while (std::cin >> town) {
      auto it = hash.find(town);
      if (it == hash.end()) {
	 std::cerr << town << " not found." << std::endl;
      } else {
	 // std::cout << it->second.population << std::endl;
	 std::cout << it->second << std::endl;
	 hash.erase(it);
	 std::cout << hash.size() << " objects left." << std::endl;
      }
   }
   for (auto& object: hash) {
      std::cout << object.first << " " << object.second << std::endl;
   }
}
theon$ g++ -std=c++17 -Wall -o testit testit.cpp
theon$ echo Freiburg Karlsruhe Heidelberg | valgrind ./testit
==3170== Memcheck, a memory error detector
==3170== Copyright (C) 2002-2017, and GNU GPL'd, by Julian Seward et al.
==3170== Using Valgrind-3.13.0 and LibVEX; rerun with -h for copyright info
==3170== Command: ./testit
==3170== 
8 objects loaded from 'cities'.
227590
7 objects left.
309999
6 objects left.
159914
5 objects left.
Konstanz 83789
Stuttgart 628032
Mannheim 304781
Ulm 123953
Tübingen 88347
==3170== 
==3170== HEAP SUMMARY:
==3170==     in use at exit: 10,256 bytes in 2 blocks
==3170==   total heap usage: 14 allocs, 12 frees, 85,104 bytes allocated
==3170== 
==3170== LEAK SUMMARY:
==3170==    definitely lost: 0 bytes in 0 blocks
==3170==    indirectly lost: 0 bytes in 0 blocks
==3170==      possibly lost: 10,256 bytes in 2 blocks
==3170==    still reachable: 0 bytes in 0 blocks
==3170==         suppressed: 0 bytes in 0 blocks
==3170== Rerun with --leak-check=full to see details of leaked memory
==3170== 
==3170== For counts of detected and suppressed errors, rerun with: -v
==3170== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 0 from 0)
theon$