그래서 개인 단어 변수로 문자열 단어와 int 빈도를 저장하는 WordFrequency라는 클래스를 만들었습니다. 해시 테이블에 WordFrequency **, hashsize, currentitems가 포함 된 HashTable 함수입니다.복사 생성자 및 getter (변경자 함수)에 오류가 발생했습니다.
난 항상 오류가 무엇입니까 복사 생성자를 사용하는 동안 - 스레드 1 : EXC_BAD_ACCESS (코드 = 1, 주소 = 0x0으로) 복사 생성자에서 호출 할 때 WordFrequency 클래스의 getter 함수에 저를 리디렉션합니다. 왜 이런 일이 일어나는지 알 수 없습니다.
복사 생성자.
Hashtable:: Hashtable(const Hashtable &hash){
WordFrequency** temp = new WordFrequency* [hash.hashSize];
this->arr = temp;
for (int i = 0 ; i < hash.hashSize ; i++) {
if (hash.arr[i] == NULL){ //pointer in hashstable is null
continue;
}
//bucket is not empty
if(this->search(this->arr[i]->getWord()) != 0 ){ //if same string already found in this hashtable
this->arr[i]->increment(); // incrtement the frequency
continue;
}
//else the string doest even exist in the hashtable.
WordFrequency x ((hash.arr[i])->getWord()); //deep copying the word from the parameter hash
temp[i] = &x; //pointing the hash table to the new the object
}
this->hashSize = hash.hashSize;
this->currentItems = hash.currentItems;
}
wordfrequency 클래스의 getter 함수.
string WordFrequency:: getWord() const {
return this->word;
}
게터 기능은 매우 간단 보이지만 나는이 오류를 얻고있다 이유를 모르겠어요.
나는 또한 문제가 될 수있는 나의 소멸자 원인을 포함하고있다.
WordFrequency x ((hash.arr[i])->getWord());
temp[i] = &x;
메모리 밖에 회수 가도록 -
Hashtable:: ~Hashtable() {
for (int i = 0 ; i < this->hashSize ; i++){
delete this->arr[i];
}
delete [] this->arr;
this->hashSize = 0;
this->currentItems = 0;
}
출력 연산자 해시 테이블 생성자의 for 루프에서
ostream& operator<< (ostream &out, const Hashtable &h){
out << "Hashtable with size - " << h.hashSize << "and no of elements - " << h.currentItems << endl;
for (int i = 0 ; i < h.hashSize ; i++){
if (h.arr[i] == NULL){
out << "0";
continue;
}
else {
out << ((h.arr[i])->getWord()); //bad access
}
}
out << endl;
return out;
}
std :: vector를 사용하십시오! –
_ "항상 오류가 발생합니다 - 스레드 1 : EXC_BAD_ACCESS"_ OK, 그리고 환경에서 디버거를 실행하고 함수 인수 값을 사용하여 해당 오류로 연결되는 정확한 스택 추적을 볼 수 있습니다. 당신은 당신의 접근이 왜 나쁜지 깨달을 수 있습니다. –
할당에 의해 사용자 지정 해시 테이블을 사용해야한다고 가정합니까? 그렇지 않다면'std :: map' 또는'std :: unordered_map'으로 많은 문제를 해결할 수 있습니다. – user4581301