I have a class that is inserting nodes with these functions:
In Node.h
class Node
{
public:
...
void insertChild(Node *child);
vector<Node *> children();
vector<Node *> _children;
};
In Node.cpp
void Node::insertChild(Node *child){
_children.push_back(child);
}
vector<Node *> Node::children(){
return _children;
}
In Trie.h
class Trie
{
public:
Node *getRoot() const;
Node *root;
void addWord(string prefix);
}
In Trie.cpp
Trie::Trie()
{
root = new Node();
}
Node *Trie::getRoot() const
{
return root;
}
void Trie::addWord(string prefix){
Node *current = root;
if(prefix.length() == 0)
{
current->setTypeMarker(DAT_NODE);
return;
}
for(int i = 0; i < prefix.length(); i++){
Node *child = current->lookupChild(prefix[i]);
if(child != NULL)
{
current = child;
}
else
{
Node *tmp = new Node();
tmp->setContent(prefix[i]);
current->insertChild(tmp);
current = tmp;
}
if(i == prefix.length()-1)
current->setTypeMarker(DAT_NODE);
}
}
In another class, I want to iterate over _children so I have
In OtherClass.h
class OtherClass
{
public:
Trie *trie;
void addWords(string word)
void someFunction()
}
In OtherClass.cpp
OtherClass::OtherClass()
{
tree = new Trie();
}
void OtherClass::addWords(string word)
{
tree->addWord(word);
}
void OtherClass::someFunction()
{
Node *root = tree->getRoot();
for(std::vector<Node *>::iterator it = root->children().begin(); it != root->children().end(); it++) {
Node * test = *it;
}
}
However, when I run this, test is nil. I can look at root and see that children contains my Nodes, but how come I can't de-reference them in the vector iterator? children()
is my getter for _children
May be your getter return std::vector by value not by the reference?
The getter should look like this:
std::vector<Node*>& Node::children()
{
return _children;
}
or for const version like this:
const std::vector<Node*>& Node::children() const
{
return _children;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.