尝试使用C++中的模板进行BST排序,但在使用随机字符串进行测试时不起作用

Try to BST Sort using template in C++ but didn't work while using random string to test

本文关键字:随机 字符串 不起作用 测试 BST C++ 排序      更新时间:2023-10-16

>我正在尝试创建二进制搜索树,然后遍历以使用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)键标记为整数。