c++ - 从 C++ 中的 vector 取消引用指向对象的指针

标签 c++ pointers vector

我有一个使用这些函数插入节点的类:

在 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

setter/getter

最佳答案

可能是您的 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/

相关文章:

c++ - 在制作 map 的情况下是否值得使用 vector

c++ - 函数 'Summation' 的参数太少

c++ - 我怎样才能消除这段代码中的全局变量?

c++ - 从列表/ map 自动生成条件表达式

c++ - 确保枚举对应某种模板类型

c - 什么时候应该使用指针分配给 int?

c - 尝试取消引用指针 : C 时出现段错误

c++ - std::vector<bool> 保证默认所有条目为假?

c++ - 将 vector 复制到数组?

C++:优化列表