patterncppMinor
C++ Trie Implementation
Viewed 0 times
implementationtriestackoverflow
Problem
I recently tried a basic C++ implementation of a Trie, and was looking for some feedback on my code style/choices. In particular I was wondering if I'd made the right choice spitting the program up into header files and using classes instead of structs.
Inside the main.cpp there is a very basic string permutation function that checks, upon each permutation, whether or not the word-prefix is possible (i.e. The permutation "abx" would be terminated). This program looks for words with a minimum length of 4 characters.
Here is a dictionary file.
DictTrie.h
DictTrie.cpp
TrieNode.h
Tri
Inside the main.cpp there is a very basic string permutation function that checks, upon each permutation, whether or not the word-prefix is possible (i.e. The permutation "abx" would be terminated). This program looks for words with a minimum length of 4 characters.
Here is a dictionary file.
DictTrie.h
/**
* File: DictTrie.h
* Author: freman
*/
#include
#include
#include "TrieNode.h"
#ifndef DICTTRIE_H
#define DICTTRIE_H
class DictTrie {
public:
DictTrie();
virtual ~DictTrie();
bool containsWord(std::string str);
bool containsPrefix(std::string str);
void insert(std::string str);
private:
TrieNode* root;
};
#endif /* DICTTRIE_H */DictTrie.cpp
/**
* File: DictTree.cpp
* Author: freman
*
* Created on 18 March 2015, 8:45 AM
*/
#include "DictTrie.h"
using std::string;
DictTrie::DictTrie() {
root = new TrieNode();
}
DictTrie::~DictTrie(){ }
bool DictTrie::containsPrefix(string str) {
return root->containsPrefix(root, str);
}
bool DictTrie::containsWord(string str) {
return root->containsWord(root, str);
}
void DictTrie::insert(string str) {
root->put(root, str);
}TrieNode.h
/*
* File: TrieNode.h
* Author: freman
*/
#include
#include
#ifndef TRIENODE_H
#define TRIENODE_H
class TrieNode {
public:
TrieNode();
virtual ~TrieNode();
TrieNode(char letter);
void put(TrieNode* root, std::string str);
bool containsWord(TrieNode* root, std::string str);
bool containsPrefix(TrieNode* root, std::string str);
private:
char letter;
bool isWord;
std::vector children;
void addChild(TrieNode* child);
TrieNode* contains(TrieNode* root, std::string str);
};
#endif /* TRIENODE_H */Tri
Solution
First thing, memory leak if you delete
There is no need for the contains functions of
The
DictTrie; use a std::unique_ptr to hold the root. Same for the children; use a std::vector >.There is no need for the contains functions of
TrieNode to take a root for it's first parameter instead use this.The
children vector could be sorted by the letter to allow you to do a binary search for O(log n) per child, or you can use the char value as index and pre-size the vector to 256 for a O(1) lookup per child.Context
StackExchange Code Review Q#94733, answer score: 5
Revisions (0)
No revisions yet.