The new forums will be named Coin Return (based on the most recent vote)! You can check on the status and timeline of the transition to the new forums here.
The Guiding Principles and New Rules document is now in effect.

c++ stl queues

YumOrgansYumOrgans Registered User new member
edited November 2007 in Help / Advice Forum
Ok, so I'm having a bit of a problem with queues/trees in c++.

In the first loop of this code, the first 2 elements of a queue are taken and attached as children of a temp "tPtr".
The "tPtr"s are then pushed into a second queue.

The process happens again, except this time the elements go from the second queue to the first.
Then back again, etc.

This happens until there is 1 element left in the queues.

The problem is that the LEFT element of the FIRST element of q1 (on second pass) somehow always gets reset to point back to itself, even though the rest of the tree works fine, for example:

A->Left = B
B->Left = A
A->Left = B

...

but the rest works fine:

A->Right = C
C->Left = D
C->Right = E

...

The strangest thing about it is that everything goes fine while debugging, until I get to the last line ( q1.push( tPtr ) );
in the debugger the tPtr is pointing to the right data, but as soon as it gets pushed into the queue, it points somewhere else. That only happens for the first element.

Any ideas?
                queue< CTree > q1;
		queue< CTree > q2;
		CTree tPtr;
		CTree *node;

		while( q1.size() + q2.size() > 1 )
		{
			while( q1.size() > 0 )
			{
				node = new CTree();
				node = &q1.front();

				tPtr.pLeft = node;
				q1.pop();

				if( q1.size() > 0 )
				{
					node = new CTree();
					node = &q1.front();

					tPtr.pRight = node;
					q1.pop();
				}

				q2.push( tPtr );
			}

			while( q2.size() > 0 )
			{
				node = new CTree();
				node = &q2.front();

				tPtr.pLeft = node;
				q2.pop();

				if( q2.size() > 0 )
				{
					node = new CTree();
					node = &q2.front();

					tPtr.pRight = node;
					q2.pop();
				}

				q1.push( tPtr );
			}
		}

YumOrgans on

Posts

  • ecchiecchi Registered User regular
    edited November 2007
    I don't have time to analyze your algorithm or implementation directly right now, but you should know that
    node = new CTree();
    node = &q1.front();
    
    is a memory leak. You're allocating space for a new node, and then overwriting the pointer to that space so you can't free it later.

    You're also doing things in a kind of weird way. Generally a variable named tPtr should be, well, a pointer. And when dealing with queues/lists/etc of objects, it's usually better to make it a queue of pointers to objects instead of just objects.

    ecchi on
Sign In or Register to comment.