this post was submitted on 13 Sep 2023
8 points (100.0% liked)

C++

1763 readers
1 users here now

The center for all discussion and news regarding C++.

Rules

founded 1 year ago
MODERATORS
 

I was trying to creating a red-black tree, and when trying to get data out of it, it always returned the same value, so i decided to try to create a very simple binary search tree, and i got the same result, so i wonder, ¿what i'm doing wrong when trying to create trees in c++? Here is the code: https://pastebin.com/L2yJJ3Nu

top 8 comments
sorted by: hot top controversial new old
[–] lawmurray@programming.dev 3 points 1 year ago* (last edited 1 year ago) (1 children)

Your get() function will always just return the value of the root node. I think you mean to have return get(value, ...) in each of its if statements.

[–] prettydarknwild@lemmy.world 2 points 1 year ago (1 children)
[–] lawmurray@programming.dev 2 points 1 year ago (1 children)

Nice, good luck with it from here!

[–] prettydarknwild@lemmy.world 1 points 1 year ago

i managed to do it (or thats what i think), the tree apparently works, but i dont know if its balanced, can you have a look at my code? i want to know if my tree is balanced correctly, here is the code: https://pastebin.com/ineG07b2 (PS: im aware that this code doesnt guarantee that the root will be black, the wikipedia article says that the black root is not a strict requirement by all the authors, so i decided to omit that)

[–] DolphinitelyJoe@lemmy.zip 2 points 1 year ago (1 children)

In the get() function, instead of if{}... if{}... return it should be if{}... else if{}... else {return...}

[–] lawmurray@programming.dev 1 points 1 year ago

This would be better style in my opinion, but by way of correctness it seems the more fundamental issue is "return" missing in the if... else if... blocks.

[–] bahbah23@lemmy.world 2 points 1 year ago (1 children)

It's been a while since I did c++.

Does make_shared make a copy of the object and return a shared pointer to it, or does it read the memory location of the variable passed to it? The node is being created on the stack, which in this simple application will likely always be at the same memory location.

[–] prettydarknwild@lemmy.world 1 points 1 year ago

yup, it does that