Sort function calls destructor?

Pages: 12
Fixed. I have just spent about 1 hour figuring this out,and I found the error. I forgot to pass the head pointer of my linked list as pointer reference, (I passed it as pointer only) and that is why that pointer never changed,and later gave me some garbage values, since it pointed to destroyed stuff. :)

Hello guys. I rewrote the code and I used linked lists instead of vectors. Anyway, I wrote the function which kills half of bunnies (randomly chosen) when population exceeds 10,but it isn't working properly. Any comments?

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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
void FoodShortage(Bunny * const head, int & tot)         
    {
        if(tot>=10)
        {
            std::ofstream FileOut ("Bunny_Output.txt",std::ios::app);
            std::cout<<"------Food shortage occured!------\n";
            FileOut <<"------Food shortage occured!------\n";
            int half=tot/2;
            Bunny * current=head;
            Bunny * temp=current;
            int random;
            for(int i=0; i<half ;i++)
            {
                current=head;
                random=GetRandom(tot-1)+1;
                std::cout<<"random is "<<random<<"\n";
                for(int j=1;j<random;j++)
                {
                    temp=current;
                    current=current->Next;
                }
                temp->Next=current->Next;
                current->~Bunny();
                tot--;
                std::cout<<"Total is: "<<tot<<std::endl;
                FileOut<<"Total is: "<<tot<<std::endl;
            }
            FileOut.close();
        }
    }

int main()
{

    int Total=1;
    int TotalVampires=0;
    srand(time(0));
    Bunny * head=NULL;
    Bunny * last=NULL;
    head=new Bunny(TotalVampires);
    last=head;
    int pause;
    for(int i=0;i<4;i++)
    {insertFirstBunny(last,Total,TotalVampires);}

    time_t start,finish,TimeElapsed;
    for(int turn=1; ;turn++)
    {

        std::cout<<"Turn number: "<<turn<<"."<<std::endl;


        printBunnies(head,Total,turn,TotalVampires);
        ageUp(head);
        insertBunny(head,last,Total,TotalVampires);
        removeBunny(head,Total,TotalVampires);
        FoodShortage(head,Total);
        becomeVampire(head,Total,TotalVampires);




        if(isEmpty(head))
        {
            std::ofstream FileOut("Bunny_Output.txt",std::ios::app);
            std::cout<<"\nALL BUNNIES DIED!\n";
            FileOut<<"\nALL BUNNIES DIED!\n";
            break;
        }
    }

    return 0;
}

Last edited on
Is there a compelling reason why a custom linked list is being preferred over std::list<>?
Topic archived. No new replies allowed.
Pages: 12