Problem with a simple queue class

Hi!

For an assignment I have to implement a simple queue using a class.

I'm having problem with this assignment though. The queue I wrote actually handles the data in first-in-last-out ( FILO ) order. So it's more a stack then a queue.

The problem is that I can't figure out why it works in this way; If I look at my program I would really be sure that I'm doing things correctly. But for some reason I don't.

Here is the code for my class:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
const unsigned int MAX_QUEUE_SIZE ( 100 );

class queue
{
    private:
        int items[MAX_QUEUE_SIZE];
        unsigned int count;
    public:
        queue ( );
        queue ( queue & old_queue );
        void put ( int item );
        int get ( );
};

queue::queue ( )
{
    count = 0;
}

queue::queue ( queue & old_queue )
{
    unsigned int index;
    
    for ( index = 0; index < old_queue.count; ++index )
    {
        items[index] = old_queue.items[index];
    }
    
    count = old_queue.count;
}

void queue::put ( int item )
{
    items [ count ] = item;
    ++count;
}

int queue::get ( )
{
    int item_to_return = items[0];
    unsigned int index;
    
    for ( index = 0; index < count; ++index )
    {
        items [ index ] = items [ index + 1 ];
    }
    --count;
    
    return ( item_to_return );
}


Here is the code I test my class with:
1
2
3
4
5
6
7
    queue a_queue;
    
    a_queue.put ( 6 );
    a_queue.put ( 8 );
    
    cout << "6-> " << a_queue.get ( ) << '\n'
         << "8-> " << a_queue.get ( ) << "\n\n";


To give you a better idea of the situation, the output of these lines of code should be:
1
2
6-> 6
8-> 8


But it actually is:
1
2
6-> 8
8-> 6


Can someone help me solve this problem?

Thanks in advance :)
Hello JoshuaS,

That is because of the order of evaluation. Means the last 'get()' is called first. So don't modify the contents of a class within a get() function. better break it in 2 function like top() and pop().

do you know that stl already provides stack and queue?
Thanks for the answer.

And your answer was the solution. I rewrote the testing code to the following and it works:
1
2
3
4
5
6
7
    queue a_queue;
    
    a_queue.put ( 6 );
    a_queue.put ( 8 );
    
    cout << "6-> " << a_queue.get ( ) << '\n';
    cout << "8-> " << a_queue.get ( ) << "\n\n";


Nevertheless, this behaviour is extremely odd and I wonder where this behaviour would be useful.

I also know about the queue class the STL provides. But this isn't production code, it's just an exercise we needed to do to practise writing useful classes :)

You may want to modify your queue so get() an put() work in constant time.
Just keep two indices (top, bottom) and use modulo operator to recycle the cells
Topic archived. No new replies allowed.