|
Hi, its been a while since I've used CodeProject.
Quick Question.
I'm training myself on standard algorithms and trying to create a linked list.
In Java it's easy.
class Node{
public int data;
public Node next;
public Node(int val){ data= val; next = null;}
}
In the C++ Pre Ox11 you could use raw pointers.
struct Node{
int data;
Node* next;
Node(int val):data(val),next(0){}
}
but you had to new up your next node and delete it afterwards.
With the new version of C++, you can use unique_ptr.
But if I try to use that, I can't seem to get a good node to next.
struct node{
int data;
unique_ptr<node> next;
node(int al):data(val),next(nullptr){}
}
node a(3);
node b(4);
a.next = b; a.next = move(b); a.next.reset (b);
Please could you enlighten me, on how I can get this to work.
Many Thanks
Tom
|
|
|
|
|
Hm... Try it :
node a(3); a.next = new node(4); a.next->next = new node(5); a.next = move(a.next->next); unique_ptr<node> temp = move(a.next->next);
a.next = move(temp);
PS: any pre 0x11 C++ strcture or class may have a destructor as well :
struct node {
int m_iData;
node* m_pNext;
node(int iData) : m_iData(iData), m_pNext(NULL) {}
~node() { delete m_pNext; }
node* detach() { node* prevNext(m_pNext); m_pNext = NULL; return prevNext; }
} a(3);
They sought it with thimbles, they sought it with care;
They pursued it with forks and hope;
They threatened its life with a railway-share;
They charmed it with smiles and soap.
modified 19-Nov-12 17:07pm.
|
|
|
|
|
I'm just guessing but the statement
a.next = b; looks like it should generate some kind of type mismatch error. At the very least I think you would have to deliberately cast 'b' to something before you can assign it to a unique_ptr variable. I'm not sure about the other two errors.
Chris Meech
I am Canadian. [heard in a local bar]
In theory there is no difference between theory and practice. In practice there is. [Yogi Berra]
posting about Crystal Reports here is like discussing gay marriage on a catholic church’s website.[Nishant Sivakumar]
|
|
|
|