yongsen / elements-of-programming-interviews

Automatically exported from code.google.com/p/elements-of-programming-interviews
Other
1 stars 0 forks source link

Problem 8.10 resize problem #11

Closed GoogleCodeExporter closed 8 years ago

GoogleCodeExporter commented 8 years ago
What steps will reproduce the problem?
Try following code with the Queue class:

int main(int argc, char *argv[]) {
    Queue<int> q;
    q.enqueue(1);
    q.enqueue(2);
    q.enqueue(3);
    q.enqueue(4);
    q.enqueue(5);
    q.enqueue(6);
    q.enqueue(7);
    q.enqueue(8);
    // Now head = 0 and tail = 0

    cout<<q.dequeue()<<endl;
    cout<<q.dequeue()<<endl;
    cout<<q.dequeue()<<endl;
    // Now head = 3 and tail = 0

    q.enqueue(11);
    q.enqueue(12);
    q.enqueue(13);
    // Ok till here. Now head = 3 and tail = 3

    q.enqueue(14); // now the vector (data) is resized; but the head and tail (or elements) does not change accordingly. data[tail]=data[3]=14!
    q.enqueue(15);
    q.enqueue(16);
    q.enqueue(17);
    q.enqueue(18);    
    // The elements starting from head=3 are overwriten! 

    cout<<q.dequeue()<<endl;
    cout<<q.dequeue()<<endl;
    cout<<q.dequeue()<<endl;
    cout<<q.dequeue()<<endl;
    cout<<q.dequeue()<<endl;
    cout<<q.dequeue()<<endl;
    cout<<q.dequeue()<<endl;

    return 0;
}

What is the expected output? What do you see instead?

Expected output:
1
2
3
4
5
6
7
8
11
12

The actual output:
1
2
3
14
15
16
17
18
0
0

What version of the product are you using? On what operating system?
Book version 1.2.0
Test on Ubuntu 12.04 with gcc version 4.6.3

Please provide any additional information below.
The resize operation is not correct. The operation appends zeros to the data 
but the existing elements are not rearranged. Also see my comments in the 
testing code.

Original issue reported on code.google.com by xuxie...@gmail.com on 10 May 2013 at 7:00

GoogleCodeExporter commented 8 years ago
Hey Xie Xu,

Thanks for your report! I have attached the updated version solution in here. 
Besides, I also add your test case in the file.

Original comment by TsungHsi...@gmail.com on 10 May 2013 at 8:09

Attachments: