错误C2440:'初始化':无法从'const int'转换为'int *'

时间:2012-11-27 16:06:25

标签: c++ templates pointers vector

当我尝试运行此代码时

template <typename Item, typename Key>
Item* BST<Item,Key>::search(const Key& key) const {
    for (std::size_t i = 0; i < tree.size(); ++i) {
                Item* ptr = NULL;
        if(tree[i].data == key && tree[i].occupied == true) {
            ptr = tree[i].data;
            return ptr;
        }
    }
    return ptr;
}

我最终得到了标题中描述的错误。我已多次尝试修复它,但无法弄清楚我做错了什么。对于某些背景信息,树是节点的向量。每个节点都有一个布尔变量,说明它是否被占用,以及一个名为data的Item变量。该函数应该在向量中搜索具有给定键的节点,并返回指向它的数据的指针,但我无法弄清楚它的生命。

1 个答案:

答案 0 :(得分:4)

看起来tree[i].data的类型是const int而不是int*。代码应将其地址存储到ptr中,并可能返回const Item*。更好的是,返回指向节点的迭代器或者如果找不到节点则返回序列结束迭代器。

相关问题