Can someone give me an example about how to define a new type of struct in a class in C++.
Thanks.
Yes you can. In c++, class and struct are kind of similar. We can define not only structure inside a class, but also a class inside one. It is called inner class.
As an example I am adding a simple Trie class.
class Trie {
private:
struct node{
node* alp[26];
bool isend;
};
node* root;
node* createNode(){
node* newnode=new node();
for(int i=0; i<26; i++){
newnode->alp[i]=nullptr;
}
newnode->isend=false;
return newnode;
}
public:
/** Initialize your data structure here. */
Trie() {
root=createNode();
}
/** Inserts a word into the trie. */
void insert(string word) {
node* head=root;
for(int i=0; ialp[int(word[i]-'a')]==nullptr){
node* newnode=createNode();
head->alp[int(word[i]-'a')]=newnode;
}
head=head->alp[int(word[i]-'a')];
}
head->isend=true;
}
/** Returns if the word is in the trie. */
bool search(string word) {
node* head=root;
for(int i=0; ialp[int(word[i]-'a')]==nullptr){
return false;
}
head=head->alp[int(word[i]-'a')];
}
if(head->isend){return true;}
return false;
}
/** Returns if there is any word in the trie that starts with the given prefix. */
bool startsWith(string prefix) {
node* head=root;
for(int i=0; ialp[int(prefix[i]-'a')]==nullptr){
return false;
}
head=head->alp[int(prefix[i]-'a')];
}
return true;
}
};
/**
* Your Trie object will be instantiated and called as such:
* Trie* obj = new Trie();
* obj->insert(word);
* bool param_2 = obj->search(word);
* bool param_3 = obj->startsWith(prefix);
*/