2012-11-15 2 views
-1

문자열에 값을 할당하는 데 어려움이 있습니다. 문자열은 구조체에 포함됩니다. 여기에 전체 코드가 있습니다.Segfault at string :: assign

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

내가 아주 많이 도움을 주셔서 감사합니다 :

그것은 운영자에 []

실패 주로 불완전 (내 반복자를 고정하기 전에 작동이를 얻으려고)입니다!

은 ~ 당신의 생성자에서

+0

나는 해시 맵 로 해시 맵을 만들 때이 작품 유의해야하지만 (가장 간단한 솔루션으로) 대신 std::vector::reservestd::vector::resize를 사용해서는 안되는 HashMap <문자열, 문자열> – user1662285

+0

, 더주세요 콘크리트. 적어도 세그 폴트를 유발하는 기능은 무엇입니까? – Lol4t0

+0

죄송합니다. 그것의 연산자 [] – user1662285

답변

1

희망 컴퓨터 과학 학생 당신은

array.reserve(arraySize); 

하지만 std::vector::reserve은 쉽게 배열 확장을위한 일부 메모리를 보유하고 요소를 생성하지 않습니다 (나 배열의 크기를 조정)을 사용합니다. 그래서 세포가 만들어지지 않습니다.

배열에 무언가를 할당하려고하면 실제로 배열 범위를 벗어납니다.

당신은

array.resize(arraySize);