i new c++ stl , learning ebooks , online sources. wanted create list of objects, initialise them using ::interator , list.insert() , display values stored in each object. here 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 2 step initialise numbers n=*temp; listofobjects.insert(it,n); it++; } for(it=listofobjects.begin();it!=listofobjects.end();it++) { it->display(); } }
so have 2 questions: 1) did initialise objects correctly? 2) when ran program, program output started 32. shouldn't start 1?
no did not initialize list correctly. code leaks memory.
your code:
1) allocates new instance of numbers
class using new
.
2) makes copy of instantiated object
3) inserts copy object std::list
.
so, new
-ed object gets leaked. thing needed was:
listofobjects.insert(it, numbers(i, j, k));
now, far reason why order wrong, it's because of related reason -- iterator insert position not being incremented correctly. insertion should be:
= ++listofobjects.insert(it, numbers(i, j, k));