C++如何访问从函数返回的对象的数据成员?

标签 c++ avl-tree

我有以下代码,它只是检查 AVL 树中是否已经存在单词/键。如果是,则返回指向该节点的指针,否则返回 null:

void fileInput::testFunction() {
    node newWord;
    newWord.key = "test";
    newWord.wordCount = 1;
    tree.AVL_Insert(newWord);
    if ((verifyWord("test").wordCount) != NULL) {
        //insert increment wordCount code here;
    }
}

这是节点结构:

struct node {
    string key;
    int wordCount;
};

这是verifyWord函数

node fileInput::verifyWord(string a) {
    node b;
    tree.AVL_Retrieve(a, b);
    return b;
}

这是 AVL_Retreive 函数:

template <class TYPE, class KTYPE>
bool   AvlTree<TYPE, KTYPE>
   ::  AVL_Retrieve  (KTYPE   key, TYPE& dataOut)
{
    NODE<TYPE> *node;

    if (!tree)
       return false;

    node    = _retrieve (key, tree);
    if (node)
       {
        dataOut = node->data;
        return true;
       } // if found
    else
       return false;
}   //  AVL_Retrieve

我的问题是如何在 testFunction() 的 if 语句中增加返回对象的 wordCount

最佳答案

您需要更改每个函数中的代码,以便 AVL_Retrieve() 在找到节点时返回指向该节点的指针,如果找不到则返回 NULL。然后 verifyWord() 将返回完全相同的指针。然后您可以使用该指针修改节点。像这样:

if (node* nn = verifyWord("test")) {
    nn->wordCount++;
}

node* fileInput::verifyWord(string a) {
    return tree.AVL_Retrieve(a);
}

template <class TYPE, class KTYPE>
TYPE* AvlTree<TYPE, KTYPE>
   ::  AVL_Retrieve  (KTYPE   key)
{
    if (!tree)
       return NULL;

    if (NODE<TYPE> *node = _retrieve (key, tree))
        return node->data;
    else
        return NULL;
}

关于C++如何访问从函数返回的对象的数据成员?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37128039/

相关文章:

c++ - 构建 MongoDB 时出现 boost::date_time 错误:winapi 不是成员

c++ - "result type must be constructible from value type of input range"创建 std::vector 时

algorithm - 构建数据结构

c - 遍历树时返回错误

c++ - 如何旋转树或 AVL 树?

c++ - 如何编写具有可选 Eigen::Ref 输出参数的函数?

c++ - GLIB 安装后无法编译基本 GLIB 程序

c - C中如何知道avl节点状态?

c++ - 为什么在循环中调用 ReadConsole 会破坏堆栈?

data-structures - 纯函数映射和集合的统计性能