问题描述
我正在尝试使用模板实现改进的广度优先搜索/深度优先搜索算法。我真的不知道该怎么做,我已经有一段时间没有使用模板了。
所以...该算法采用一个 tree
类型的参数 std::shared_ptr<BinarySearch>
(BinaryTree
是具有左右智能指针、构造函数和一些方法的树的类代码) 和一个整数,即要找到的值。
在算法的一种情况下,我想返回一个 nullptr
指针(意味着树为空),而在其他情况下,如果找到或未找到值,则返回 true 或 false。
到目前为止,我在 VS 2019 中遇到了这些错误:
C2672:'find_i':找不到匹配的重载函数
C2784 'T find_i(T,T)':无法从'int'推导出'T'的模板参数
C2782:'T find_i(T,T)':模板参数'T'不明确
E0304:没有函数模板“find_i”的实例与参数列表相匹配
用于 BST 的代码:
class Node
{
public: // provide public access
int data;
std::shared_ptr<Node> left; // use smart pointers
std::shared_ptr<Node> right; //
Node(int _data = 0) : // constructor +
data(_data),// initialization list for the attributes
left(nullptr),right(nullptr)
{}
};
class BinaryTree
{
public: // provide public access
std::shared_ptr<Node> root;
BinaryTree() : root(nullptr) {}; // constructor + initialization list
// for the attribute
void insert(int data)
{
if (root == nullptr)
root = std::make_shared<Node>(data); // allocate the pointer
else
_insert(data,root);
}
void _insert(int data,std::shared_ptr<Node> cur_node)
{
if (data < cur_node->data)
{
if (cur_node->left == nullptr)
cur_node->left = std::make_shared<Node>(data); // allocate the pointer
else
_insert(data,cur_node->left);
}
else if (data > cur_node->data)
{
if (cur_node->right == nullptr)
cur_node->right = std::make_shared<Node>(data); // allocate the pointer
else
_insert(data,cur_node->right);
}
else
std::cout << "Value already present in tree" << std::endl;
}
}
BFS/DFS 改进算法:
template<typename T>
T find_i(T tree,T target)
{
std::shared_ptr<Node> cur_node = tree->root;
if (cur_node == nullptr)
return nullptr;
while (cur_node != nullptr)
{
if (cur_node->data == target)
return true;
else if (cur_node->data > target)
cur_node = cur_node->left;
else
cur_node = cur_node->right;
}
return false;
}
驱动程序代码:
int main()
{
// driver code
std::shared_ptr<BinaryTree> bst = std::make_shared<BinaryTree>();
//bst->insert(5);
//bst->insert(3);
//bst->insert(8);
//bst->insert(1);
//bst->insert(4);
//bst->insert(6);
//bst->insert(12);
bst->insert(25);
bst->insert(15);
bst->insert(33);
bst->insert(17);
bst->insert(12);
bst->insert(18);
bst->insert(16);
bst->insert(9);
bst->insert(26);
bst->insert(47);
bst->insert(95);
bst->insert(35);
bst->insert(55);
bst->insert(100);
bst->insert(87);
//bst->display(bst->root);
//bst->remove(bst,33);
bst->display(bst->root);
auto f = find_i(bst,33);
//std::cout << std::endl;
//if (f == true)
std::cout << "Value found";
return 0;
}
问题是我只想根据给定的情况返回 2 种不同的返回类型,参数将始终几乎相同。
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)