The Trie data structure
Jan 31, 2022 at 1:24am UTC
I'm trying to digest the code from this site:
https://www.techiedelight.com/cpp-implementation-trie-data-structure/
I'm currently stuck near the beginning:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
#include <iostream>
using namespace std;
// Define the character size
#define CHAR_SIZE 128
// A class to store a Trie node
class Trie
{
public :
bool isLeaf;
Trie* character[CHAR_SIZE];
// Constructor
Trie()
{
this ->isLeaf = false ;
for (int i = 0; i < CHAR_SIZE; i++) {
this ->character[i] = nullptr ;
}
}
void insert(string);
bool deletion(Trie*&, string);
bool search(string);
bool haveChildren(Trie const *);
};
Can someone please confirm what this line does:
Trie* character[CHAR_SIZE];
Does this mean each object of the Trie class, will have an array of 128 pointers to other Trie objects?
Jan 31, 2022 at 2:14am UTC
yes, it means that each one can potentially have 0 to 128 children.
Jan 31, 2022 at 9:56am UTC
Note that if you initialise the variables when defined, the constructor can be vastly simplified:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
#include <iostream>
using namespace std;
// Define the character size
constexpr size_t CHAR_SIZE {128};
// A class to store a Trie node
class Trie {
public :
bool isLeaf {};
Trie* character[CHAR_SIZE] {};
// Constructor
Trie() {}
void insert(const string&);
bool deletion(Trie*&, const string&);
bool search(const string&);
bool haveChildren(Trie const *);
};
You also need a destructor, a copy constructor (and preferably also a move constructor) and an assignment (operator=) function.
Note that that code has issues.
Jan 31, 2022 at 11:59am UTC
Note that that code has issues.
Politely said, many other people would call it crap.
Another good example why people shouldn't search for C++ code on the net.
Jan 31, 2022 at 12:26pm UTC
in the page's view source: datePublished":"2016-12-03T04:24:19+00:00"
probably best to not study too much code written before 2018 as a rough ballpark.
Topic archived. No new replies allowed.