2015-01-01 4 views
0
#include <iostream> 
#include <vector> 
#include <string> 

using namespace std; 

#define LOWERCASE_ALPHABET_SiZE 26 

typedef int (*ptr) (char); 

inline int charToIndex(char a) { return a - 'a'; }; 

class trienode 
{ 
    private: 
     vector< trienode* > child; 
     bool leaf; 
    public: 
     trienode(int); 
     ~trienode(); 
     void initialiseChild(int i); 
     trienode* getChild(int i); 
     void setLeaf() { leaf = true; }; 
     bool isLeaf() { return leaf; }; 
}; 

trienode::trienode(int size) 
{ 
    for(int i = 0; i < size; i++) 
    { 
     child.push_back(NULL); 
    } 
    leaf = false; 
} 

trienode::~trienode() 
{ 
    for(int i = 0; i < child.size(); i++) 
    { 
     delete child.at(i); 
     child.at(i) = NULL; 
    } 
} 

void trienode::initialiseChild(int i) 
{ 
    child.at(i) = new trienode(child.size()); 
} 

trienode* trienode::getChild(int i) 
{ 
    return child.at(i); 
} 

class trie 
{ 
    private: 
     trienode* root; 
     ptr toIndex; 
    public: 
     trie(int , ptr); 
     ~trie(); 
     void insert(const string& ref); 
     bool search(const string& ref); 
}; 

trie::trie(int size, ptr toIndex) : toIndex(toIndex), root(new trienode(size)) { } 

trie::~trie() 
{ 
    cout << "In destructor trie" << endl; 
    delete root; 
    root = NULL; 
} 

void trie::insert(const string& ref) 
{ 
    int size = ref.size(); 
    trienode* root = root; 
    for(int i = 0; i < size; i++) 
    { 
     int index = toIndex(ref[i]); 
     if(root->getChild(index) == NULL) // crashing in getChild() 
     { 
      root->initialiseChild(index); 
     } 
     root = root->getChild(index); 
    } 
    root->setLeaf(); 
} 

bool trie::search(const string& ref) 
{ 
    trienode* root = root; 
    int size = ref.size(); 
    for(int i = 0; i < size && root != NULL; i++) 
    { 
     int index = toIndex(ref[i]); 
     if((root = root->getChild(index)) == NULL) 
     { 
      break; 
     } 
    } 
    return (root != NULL && root->isLeaf()); 
} 

int main(int argc,char* argv[]) 
{ 
    trie* altrie = new trie(LOWERCASE_ALPHABET_SiZE, charToIndex); 
    int n; 
    string temp; 
    cin >> n; 
    for(int i = 0; i < n; i++) 
    { 
     cin >> temp; 
     altrie->insert(temp); 
    } 
    int k; 
    for(int i = 0; i < k; i++) 
    { 
     cin >> temp; 
     if(altrie->search(temp)) 
     { 
      cout << temp << " exists in the trie" << endl; 
     } 
     else 
     { 
      cout << temp << " doesn`t exist in the trie" << endl; 
     } 
    } 
    return 0; 
} 

Я создаю Trie, не снабжая детей, которые он может иметь на каждом уровне, и указатель функции для преобразования данного символа в индекс. После этого я создаю корневой узел trie и когда я вставляю первую строку, он получает ошибку сегментации в функции getChildОшибка сегментации в реализации trie с использованием вектора C++

Прежде всего, сначала объясните причину аварии. Объясните мне, как я могу улучшить реализацию trie.

+2

Пожалуйста, прочитайте [Как отлаживать небольшие программы] (http://ericlippert.com/2014/03/05/how-to-debug-small-programs/). – honk

+0

благодарю вас за предложение. Я решил проблему –

ответ

1

Вы используете один и тот же имя для членов и локальных переменных, например:

trienode* root = root; 

Компилятор не может сказать diffirence между локальным корнем и синтаксического дерева :: корень, так что вы назначаете его к себе.

Смежные вопросы