i am using a queue..i can push the values into the queue but while retriving the values,they are empty

i am using a queue..i can push the values into the queue but while retriving the values,they are empty

the code i am using is placed below

struct SRace
{
int n;
int j;
};
void CQueeDlg::test()
{

typedef queue<SRace*> SQueue;


SQueue sque;//This is the queue

SRace *oRace=new SRace;//This is a structure

for(int i=0;i<2;i++)
{
oRace->j=i;
oRace->n=i+1;

sque.push(oRace);
}

oRace->j=0;
oRace->n=0;

oRace=sque.front();


delete oRace;

}

plz help me




Answer this question

i am using a queue..i can push the values into the queue but while retriving the values,they are empty

  • Cannan

    The problem is with your code.

    You are just keeping a pointer inside the queue. And what all modifications you have done at the location of the pointer, it will reflect in the items added with the same memory

    Here you have allocated an object using new operator.

    SRace *oRace=new SRace;//This is a structure

    On allocation oRace will have some pointer value which points to allocated (there’s also chance for out of memory conditions)

    You are iterating and adding something to the queue.

    for(int i=0;i<2;i++)
    {
    oRace->j=i;
    oRace->n=i+1;

    sque.push(oRace);
    }

    So the first item will contain 0,1 respectively as j and n right

    On the next iteration, you are again modifying the oRace object.

    Which will be 1,2 and you are adding it to the next item.

    But the problem is the first item also points to the same location because you are and accessing that location will also points to the oRace which’s current value is 1,2 and all the items in your array will pointing to the same memory location. You are not keeping any values in the queue but just a location which points to the values.

    Suppose 0xABF0 is the allocated location for oRay all your items in the queue will contain same pointer value which is 0xABF0

    Finally outside the loop you are again modifying it to 0,0.

    oRace->j=0;
    oRace->n=0;

    You again modified the memory.

    I think the code is not logical.

    Either you can add dynamically allocated pointers to the array and you can free them on exit or whenever you want. You may need to iterate and delete each pointer.

    for(int i=0;i<2;i++)

    {

    SRace *oRace=new SRace;//This is a structure

    oRace->j=i;

    oRace->n=i+1;

    sque.push(oRace);

    }

    And delete after using it.

    Or you can make your queue stored by values like follows

    for(int i=0;i<2;i++)

    {

    SRace oRace;

    oRace->j=i;

    oRace->n=i+1;

    sque.push(oRace);

    }

    You have to modify the declaration like this.

    typedef queue<SRace> SQueue;

    HTH



  • i am using a queue..i can push the values into the queue but while retriving the values,they are empty