Проблемы при написании c ++ функции split_rope - PullRequest
1 голос
/ 22 апреля 2019

Я пытаюсь написать функцию разделенной веревки для структуры данных веревки, чтобы я мог сделать вставку по функции индекса I.Я обнаружил Java-реализацию извлечения подстроки из индексов от начала до конца, и я пытаюсь использовать эти концепции из нее для создания функции C ++ для разбиения веревки

Я ссылался на статью Википедии и оригинальную статью (ссылканиже), но они довольно расплывчаты.https://en.wikipedia.org/wiki/Rope_(data_structure) http://citeseerx.ist.psu.edu/viewdoc/download?doi=10.1.1.14.9450&rep=rep1&type=pdf

Вот ссылка на код, на который я ссылаюсь: https://www.sanfoundry.com/java-program-implement-rope/

string substring(int start, int end){
            string str = "";
            bool found = false;
            Node *temp = root;
            if (end > temp->weight) {
                found = true;
                end -= temp->weight;
                if (start > temp->weight) {
                    start -= temp->weight;
                    str = temp->right->data[substring(start, end)];
                    return str;
                } else
                    str = temp->right->data[substring(0, end)];            
            }        
            if (!found){
                while (end <= temp->weight)
                    temp = temp->left;
                end -= temp->weight;
                if (start >= temp->weight){
                    start -= temp->weight;
                    str = temp->right->data[substring(start, end)] + str;
                    return str;
                }
                str = temp->right->data[substring(0, end)];            
            }    
            temp = temp->left;
            while (start < temp->weight){
                str = temp->right->data + str;
                temp = temp->left;
            }
            start -= temp->weight;
            str = temp->right->data[substring(start, end) + str];    

            return str;        
        }

Предполагается, что приведенная выше функция возвращает подстроку веревкиот начала int до конца int.Я получаю от него ошибку no operator "[]" matches these operands -- operand types are: char * [ std::__1::basic_string<char, std::__1::char_traits<char>, std::__1::allocator<char>> ].

Я хотел бы попробовать другую реализацию типа, если это возможно, но я не смог найти более подробную документацию по этой функции

По запросу, вот другой код, который я написал.Если у вас есть предложение о том, как лучше реализовать разбиение на мой код, это будет с благодарностью

class Rope {   // Rope data structure
private:

    class Node {
    public:
        char *data;
        int weight;
        Node *left, *right;
        Node(char *data) : data(data), weight(sizeof(data)/sizeof(char)), left(nullptr), right(nullptr){}
        Node() : data(nullptr), weight(0), left(nullptr), right(nullptr){}
    };

    Node* root;

public:
    Rope() : root(new Node()) {}

    // Rope(const char str[]) {}
    // Rope(const char str[], int len) {}

    void makeEmpty () {
        root = new Node();
    }

    void concat(char *str) {    // concats string and rope
        Node *temp = new Node(str);
        Node *newRoot = new Node();
        newRoot->left = root;
        newRoot->right = temp;
        newRoot->weight = newRoot->left->weight;
        if (newRoot->left->right != nullptr) {
            newRoot->weight += newRoot->left->right->weight;
        }
        root = newRoot;   
    }

    void concatRope(const Rope& r1, const Rope& r2){ // concats 2 ropes
        Node *newRoot = new Node();
        newRoot->left = r1.root;
        newRoot->right = r2.root;
        newRoot->weight = newRoot->left->weight;
        if (newRoot->left->right != nullptr){
            newRoot->weight += newRoot->left->right->weight;
        }
        root = newRoot;
    }
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...