1

スプレー ツリー用の C++ テンプレート構造体を作成しようとしていますが、コードをテストしようとすると、非常に奇妙な結果が得られます。

これはテンプレートの私のコードです:

template <class T>
struct splaytree {
    struct node {
        splaytree<T> *tree;
        node *p, *c[2];
        T v;
        int w;
        node(T t, splaytree<T> *st) {
            v = t;
            p = 0;
            c[0] = 0;
            c[1] = 0;
            w = 1;
            tree = st;
        }
        int side() {
            return (p->c[1] == this) ? 1:0;
        }
        void r() {
            node *x = this;
            int b = x->side();
            node *p = x->p;
            x->w = p->w;
            p->w = x->c[1^b]->w + 1 + p->c[1^b]->w;
            x->p = p->p;
            p->p = x;
            p->c[0^b] = x->c[1^b];
            x->c[1^b] = p;
        }
        void splay() {
            node *x = this;
            while (x->p) {
                node *p = x->p;
                if (p == tree->root) x->r();
                else if (((x->side())^(p->side()))) {
                    x->r();
                    x->r();
                }
                else {
                    p->r();
                    x->r();
                }
            }
            tree->root = this;
        }
        int index() {
            this->splay();
            return this->c[0]->w;
        }
    };
    node *root;
    splaytree() {
        root = 0;
    }
    void add(T k) {
        node x0(k,this);
        node *x = &x0;
        if (root == 0) {
            root = x;
            return;
        }
        node *i = root;
        while (i != x) {
            int b = (k < i->v) ? 0:1;
            if (i->c[b] == 0) {
                i->c[b] = x;
                i->w++;
                x->p = i;
            }
            i = i->c[b];
        }
        x->splay();
    }
};

これを使用してテストしています:

int main() {
    splaytree<int> st;
    st.add(2);
    cout << st.root->v << endl;
    cout << st.root->v << endl;
    st.add(3);
    cout << st.root->c[0] << endl;
}

要素 2 を挿入し、ルート ノードの値を 2 回出力しました。どういうわけか、2 つのプリントから 2 つの異なる値が得られました ( http://ideone.com/RxZMyAの Ideone では 2 と 10 )。コンピューターでプログラムを実行すると、代わりに 2 と 1875691072 が返されました。どちらの場合も、2 の後に 3 を挿入すると、ルート ノードの左の子は、2 を含むノード オブジェクトである必要があるときに null ポインターでした。

同じものを2回印刷すると2つの異なる値が得られる理由と、splaytree.add()関数を意図したとおりに機能させるためにできることを教えてください。ありがとう!

4

1 に答える 1

1

    node x0(k,this);
    node *x = &x0;
    if (root == 0) {
        root = x;
        return;
    }

rootローカル変数のアドレスです。を印刷する頃にはroot->vx0は対象外です。rootが実際に何を指しているのかについてのすべての賭けは外れています。

于 2016-09-27T20:17:59.133 に答える