繁体   English   中英

字符串比较失败 - C++

[英]String comparison fails - C++

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

崩溃消息: Access violation reading location.

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

编码:

主要的:

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

暂无
暂无

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

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