Segfault at string :: assign

时间:2012-11-15 20:33:39

标签: c++

我很难为字符串赋值。该字符串包含在结构中。这是完整的代码。它在很大程度上是不完整的(我试图在修复迭代器之前让它工作)

操作员[]

失败

#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;
    }
};

我非常感谢你的帮助!

〜一个绝望的计算机科学专业的学生

1 个答案:

答案 0 :(得分:1)

在构造函数中使用

array.reserve(arraySize);

但是std::vector::reserve只保留一些内存以便于数组扩展,并且不会创建元素(也不会调整数组大小)。所以,你的细胞不会被构建。

然后,当您尝试将某些内容分配给数组时,实际上您已经超出了数组范围。

您应该使用std::vector::resize代替std::vector::reserve(作为最简单的解决方案)

array.resize(arraySize);