I was trained in "C with Classes" style C++ and I need to rapidly get acclimated to modern C++. I am writing a very simple bst with shared_ptr
class bst
{
private:
struct node
{
int data;
shared_ptr<node> l, r;
};
shared_ptr<node> head;
int size;
public:
bst() { size = 0; }
shared_ptr<node> doinsert(shared_ptr<node> curr, int n)
{
if (curr.get() == nullptr)
{
curr.reset(new node);
curr->data=n;
size++;
}
else if (curr->data > n)
curr->l.reset(doinsert(curr->l,n).get());
else if (curr->data < n)
curr->r.reset(doinsert(curr->r,n).get());
return curr;
}
void insert(int n)
{
shared_ptr<node> temp = doinsert(head,n);
head.reset(temp.get());
}
inline int getsize() { return size; }
};
And I have a simple harness:
int main()
{
vector<int> v = {2,1,1,2,3,1};
bst temp;
for(auto i : v) temp.insert(i);
}
It looks like the first element gets inserted just fine but things go fubar after that. It wouldn't be resetting the pointer would it?
Aucun commentaire:
Enregistrer un commentaire