Smatik
Smatik

Reputation: 407

how to initialise objects in a <list> and interate them in c++? Are they randomely stored?

I am new to c++ STL and am learning from ebooks and online sources. I wanted to create a list of objects, initialise them using ::interator and list.insert() and finally display the values stored in each object. Here is the code:

#include <iostream>
#include <list>
#include <algorithm>

#define MAX 50
using namespace std;

class numbers{
    int a;
    int b;
    int c;
    int sumvar;
    int sum()
    {
        return(sumvar=a+b+c);
    }
    public:
    numbers(int a,int b,int c)
    {
        this->a=a;
        this->b=b;
        this->c=c;
    }
    void display()
    {
        cout<<a<<endl<<b<<endl<<c<<endl<<endl;
    }
};

int main()
{
    list<numbers> listofobjects;
    list<numbers>::iterator it=listofobjects.begin();
    for(int i=1;i<MAX-1;i++)
    {
        int j=i*21-4;
        int k=i*j/7;
        numbers *temp = new numbers(i,j,k); //i went through a two step initialise 
        numbers n=*temp;
        listofobjects.insert(it,n);
        it++;
    }

    for(it=listofobjects.begin();it!=listofobjects.end();it++)
    {
        it->display();
    }
}

So I have 2 questions: 1) Did I initialise objects correctly? 2) When I ran the program, the program output started from 32. Shouldn't it start from 1? enter image description here

Upvotes: 1

Views: 43

Answers (1)

Sam Varshavchik
Sam Varshavchik

Reputation: 118300

No you did not initialize the list correctly. Your code leaks memory.

Your code:

1) Allocates a new instance of the numbers class using new.

2) Makes a copy of the instantiated object

3) Inserts the copy object into the std::list.

So, the new-ed object gets leaked. The only thing you needed to do was:

    listofobjects.insert(it, numbers(i, j, k));

Now, as far as the reason why the order was wrong, it's because of a related reason -- the iterator for the insert position is not being incremented correctly. Your insertion should be:

    it = ++listofobjects.insert(it, numbers(i, j, k));

Upvotes: 1

Related Questions