尝试使用C++中的模板进行BST排序,但在使用随机字符串进行测试时不起作用
Try to BST Sort using template in C++ but didn't work while using random string to test
>我正在尝试创建二进制搜索树,然后遍历以使用C++中的模板进行排序,但是使用随机字符串数组进行测试时出现了问题。
当我使用随机整数数组进行测试时,它一切正常,但不幸的是,它在使用字符串而不是整数时显示错误消息No matching function for call to 'insert
。
#include <iostream>
#include <cstring>
#include <ctime>
using namespace std;
struct Node
{
int key;
struct Node *left, *right;
};
struct Node *newNode(int item)
{
struct Node *temp = new Node;
temp->key = item;
temp->left = temp->right = NULL;
return temp;
}
template <typename T> void storeSorted(Node *root, T *arr, int &i)
{
if (root != NULL)
{
storeSorted(root->left, arr, i);
arr[i++] = root->key;
storeSorted(root->right, arr, i);
}
}
Node* insert(Node* node, int key)
{
if (node == NULL) return newNode(key);
if (key < node->key)
node->left = insert(node->left, key);
else if (key > node->key)
node->right = insert(node->right, key);
return node;
}
template <typename T> void treeSort(T *arr, int n)
{
struct Node *root = NULL;
root = insert(root, arr[0]);
for (int i=1; i<n; i++)
insert(root, arr[i]);
int i = 0;
storeSorted(root, arr, i);
}
string *stringData(int length) {
srand(time(NULL));
string *data = new string[length];
const char *alphabet = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
for (int j = 0; j < length; j++) {
for (int k = 0; k < 6; k++)
data[j] += alphabet[rand() % strlen(alphabet)];
}
return data;
}
int main()
{
int n = 100;
string *arr = stringData(n);
treeSort(arr, n);
for (int i=0; i<n; i++)
cout << arr[i] << " ";
system("PAUSE");
return 0;
}
因为当你写insert(root, arr[i]);
时arr[i]
是字符串,你希望arr[i]
是整数,因为你Node* insert(Node* node, int key)
键标记为整数。
相关文章:
- 在c++构造函数中使用随机字符串生成器
- 尝试使用C++中的模板进行BST排序,但在使用随机字符串进行测试时不起作用
- 我可以比朴素哈希表更快地将随机字符串映射到两个类吗?
- 选择随机字符串数组的排序
- 这个随机字符串打印代码有什么问题?
- 队列快速排序不排序和打印随机字符串[C ]
- 随机字符串生成器不编辑我的字符串数组 (C++)
- 在C 11中生成一个随机字符串
- 将作为数学运算符的字符添加到随机字符串中
- 如何用非重复字母打印随机字符串
- 无法获取随机字符串
- 如何在C++中生成随机字符串
- 从文件中读取随机字符串时出错
- 随机字符串生成产生奇怪的字符
- 生成(并非如此)出现特定字符串的随机字符串
- 无输出和随机字符串数组
- 极慢的随机字符串生成器
- 检查长随机字符串(C++)中可能的英语单词
- C++随机字符串数组不起作用
- C++随机字符串返回意外结果