具有向量切片的向量指针,用于从预向量和有序向量生成树

时间:2019-04-20 01:45:50

标签: c++ vector tree

我遇到以下错误:

solution.cpp:在成员函数buildTree中 行26:字符62:错误:没有匹配的函数可以调用'Solution :: buildTree(__ gnu_cxx :: __ alloc_traits,int> :: value_type *,std :: vector *)'          root-> left = buildTree(&preorder [index],&inorderslice);                                                               ^

在此代码中:

DATABASE_URL

我正在尝试解决一个问题,即根据其前序和有序遍历向量生成树。

我正在尝试递归地执行此操作,但是在匹配执行递归的函数的变量类型时遇到了问题。


class Solution {
public:
    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {
        if(preorder.empty() || inorder.empty())
            return NULL;
        if(preorder.size() == 1) // preorder and inorder should always have the same length
        {
            TreeNode *node = new TreeNode(preorder[0]);
            return node;
        }
        // current root is the first entry of preorder
        TreeNode *root = new TreeNode(preorder[0]);
        // find the index of this number in inorder
        std::vector<int>::iterator it = std::find(inorder.begin(), inorder.end(), preorder[0]);
        int index = std::distance(inorder.begin(), it);
        std::vector<int> inorderslice = std::vector<int>(inorder.begin(), inorder.begin() + index);
        root->left = buildTree(&preorder[index],&inorderslice); // This line is a problem
        root->right = buildTree(&preorder[index+1],&inorder[index+1]); // This line is a problem
        return root;

    }
};

此标头正在接收指向整数向量的指针。

在我的算法中,我试图对输入向量进行切片,以仅在递归中使用它的一部分:

    TreeNode* buildTree(vector<int>& preorder, vector<int>& inorder) {

对于预向量,我只想剪切前面的元素(索引之前的元素),所以我认为我只是将指针传递给向量的那个元素。

对于有序向量,我想在索引之后剪切元素。

以pythonic的方式 预购[index:] inorder [:index]

但是在调用该函数时出现错误。

如何在C ++中做到这一点?

谢谢。

1 个答案:

答案 0 :(得分:0)

您的函数引用了;您正在传递指针。

这里&的含义令人困惑。

它是以下任何一个

    在两个表达式之间应用
  • 按位 AND 运算符
  • “ address-of”运算符应用于一个运算符时,产生一个指针
    • 这就是您在函数调用中所做的
  • 添加到类型名称中的“引用”
    • 这就是您要输入的函数参数

简而言之,从通话中删除&,然后阅读C ++书中有关使用引用的章节。

  

此标头正在接收指向整数向量的指针。

不,不是。