-1

文字列に値を割り当てるのに問題があります。文字列は構造体に含まれています。これが完全なコードです。ほとんど不完全です(イテレータを修正する前にこれを機能させようとしています)

operator[]で失敗します

#include <string>
#include <iostream>
#include <vector>

using namespace std;

template <class Key,class Value>
class hashMap
{
  public:
    explicit hashMap( int size = 101 ) : arraySize( size ){
      array.reserve(arraySize+1);
    }
    hashMap(const hashMap & rhs){
      arraySize = rhs.arraySize;
      array.reserve(arraySize);
      for(int i = 0; i < arraySize; i++)
      {
        array[i] = rhs.array[i];
      }
    }
    ~hashMap()
    {
    }
    hashMap & operator=(const hashMap & rhs){
      if (&rhs != this)
      {
        arraySize = rhs.arraySize;
        array.clear();
        array.reserve(arraySize);
        for(int i = 0; i < arraySize; i++)
        {
          array[i] = rhs.array[i];
        }
      }
    }
    Value & operator[](const Key & key)
    {
        unsigned long long pos = hash(key, arraySize);
        unsigned long long quad = 1;
        while (array[pos].active != false && array[pos].first != key)
        {
          pos += quad;
          pos %= arraySize;
          quad *= 2;
        }
        array[pos].first = key; // FAILS HERE
        array[pos].active = true;
        return array[pos].second;
    }

    struct cell{
      Key first;
      Value second;
      bool active;
      cell(){
        active = false;
      }
    };

    class const_iterator
    {
      public:
        cell operator*()
        {
          return array[pos];
        }
      private:
        int pos;
    };

  private:
    vector<cell> array;
    int arraySize;
    int hash(const std::string & key, int tableSize)
    {
      int hashVal = 0;

      for(int i = 0; i < key.length(); i++)
      {
        hashVal = 37 * hashVal + key[i];
      }

      hashVal %= tableSize;
      if(hashVal < 0)
      {
        hashVal += tableSize;
      }

      return hashVal;
    }
    int hash(int key, int tableSize)
    {
      return key%tableSize;
    }
};

助けていただければ幸いです!

〜絶望的なコンピュータサイエンスの学生

4

1 に答える 1

1

コンストラクターでは、

array.reserve(arraySize);

ただし、std::vector::reserve配列を簡単に拡張するためにメモリを予約するだけで、要素を作成しません(配列のサイズを変更しません)。したがって、セルは構築されません。

次に、配列に何かを割り当てようとすると、実際には配列の範囲外になります。

(最も簡単な解決策として)のstd::vector::resize代わりに使用する必要がありますstd::vector::reserve

array.resize(arraySize);
于 2012-11-15T20:50:28.937 に答える