我正在尝试为绳索数据结构编写拆分绳索函数,以便可以在索引I函数处插入。我找到了从索引开始到结束检索子字符串的Java实现,并且我试图从中使用这些概念来创建C ++函数来分割绳索
我已经引用了Wikipedia文章和原始论文(在下面链接),但是它们非常模糊。 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 start到int end返回绳索的子字符串。我收到一个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;
}