我有一个使用这些函数插入节点的类:
在 Node.h 中
class Node
{
public:
...
void insertChild(Node *child);
vector<Node *> children();
vector<Node *> _children;
};
在 Node.cpp 中
void Node::insertChild(Node *child){
_children.push_back(child);
}
vector<Node *> Node::children(){
return _children;
}
在 Trie.h 中
class Trie
{
public:
Node *getRoot() const;
Node *root;
void addWord(string prefix);
}
在 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);
}
}
在另一个类中,我想遍历 _children,所以我有
在OtherClass.h中
class OtherClass
{
public:
Trie *trie;
void addWords(string word)
void someFunction()
}
在 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;
}
}
但是,当我运行它时,测试为零。我可以查看 root 并看到 children 包含我的节点,但为什么我不能在 vector 迭代器中取消对它们的引用? children()
是我的 _children
最佳答案
可能是您的 getter 按值而不是按引用返回 std::vector?
getter 应该是这样的:
std::vector<Node*>& Node::children()
{
return _children;
}
或者像这样的 const 版本:
const std::vector<Node*>& Node::children() const
{
return _children;
}
关于c++ - 从 C++ 中的 vector 取消引用指向对象的指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18646102/