简体   繁体   English

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

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

I am trying to creat binary Search Tree then traversal by in-order to sort with template in C++ but there is something wrong when testing with random string array.我正在尝试创建二叉搜索树,然后按顺序遍历 C++ 中的模板,但是在使用随机字符串数组进行测试时出现问题。

It working all properly when I test with random integer array, but unfortunately it shows error message No matching function for call to 'insert while using string instead of integer.当我使用随机整数数组进行测试时,它一切正常,但不幸的是,它显示错误消息No matching function for call to 'insert while using string 而不是 integer。

#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;
}

Because when you write insert(root, arr[i]);因为当你写insert(root, arr[i]); where arr[i] is string you expect to arr[i] be integer because you marked Node* insert(Node* node, int key) your key as integer.其中arr[i]是您希望arr[i]为整数的字符串,因为您将Node* insert(Node* node, int key)标记为整数。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM