字符串比较失败-C++

String comparison fails - C++

本文关键字:-C++ 失败 比较 字符串      更新时间:2023-10-16

当我试图向二进制搜索树添加新节点时,我的程序崩溃。

崩溃消息:Access violation reading location.

xstring: return (compare(0, this->_Mysize, _Right._Myptr(), _Right.size())); 中的线路

代码:

main:

BSNode* bs = new BSNode("6");
bs->insert("2");
bs->insert("8");

崩溃的功能:

if (value.compare(_data) > 0)
{
    if (this->isLeaf())
    {
        _right = new BSNode(value);
    }
    else
    {
        _right->insert(value);
    }
}
else if (value.compare(_data) < 0)
{
    if (this->isLeaf())
    {
        _left = new BSNode(value);
    }
    else
    {
        _left->insert(value);
    }
}

它在第1行"if(value.compare(_data)>0)"处崩溃。

更多代码:

BSNode::BSNode(string value)
{
    _data = value;
    _right = NULL;
    _left = NULL;
}

谢谢,奥马尔。

它运行良好。。。

#include "BSNode.h"
BSNode::BSNode(string value)
{
    _data = value;
    _right = NULL;
    _left = NULL;
}
void BSNode::insert(string value) 
{
    if (value.compare(_data) < 0)
    {
        if (_left->is_empty())
        {
            _left = new BSNode(value);
        } else {
            _left->insert(value);
        }
    } else
    if (value.compare(_data) > 0)
    {
        if (_right->is_empty())
        {
            _right = new BSNode(value);
        } else {
            _right->insert(value);
        }
    }
}
bool BSNode::is_empty()
{
    return (this == NULL);
}
bool BSNode::is_leaf()
{
    return (!this->is_empty() && _left->is_empty() && _right->is_empty());
}
void BSNode::print_bfs() 
{
    queue<BSNode*> queue;
    queue.push(this);
    BSNode * tmp;
    while (!queue.empty())
    {
        tmp = queue.front();
        queue.pop();
        if (tmp->is_empty())
            continue;
        cout << tmp->_data << ", ";
        queue.push(tmp->_left);
        queue.push(tmp->_right);
    }
    cout << endl;
}