i have a stl list of myclass and a pointer to a myclass-objects. now i do listofmyclass.push_back() to create one object of myclass. how can i now assign the pointer to the myclass-object to the new object that was just created?
mypointer = &mylist.back();
listofmyclass.push_back() is invalid C++ code. You need to push back some object. If you do that you have a pointer to it.
You can do this:
listofmyclass.push_back( MyClass() ); MyClass* = &(*listofmyclass.rbegin());
I believe.
mypointer = &mylist.back();
sounds good i'll test it.
i tried to do mypoiter=&mylist.begin(); but that didn't work. i think there is also a member called pointer in the stl list class but don't know how to access it.
and how to access a pointer that is the second one of three elements for example?
But if you do this:
list<MyClass> listofmyclass; MyClass* mc = new MyClass(); listofmyclass.push_back(*mc); mc = &listofmyclass.back();
you'll leak memory. The memory allocated in line 2 is copied to a new list entry in line 3. Then the pointer is set to the copy in line 4, leaving the original data allocated, but unreferenced.
Correctly, you would either:
list<MyClass> listofmyclass; MyClass* mc = new MyClass(); listofmyclass.push_back(*mc); delete mc; mc = &listofmyclass.back();
or:
list<MyClass*> listofmyclass; MyClass* mc = new MyClass(); listofmyclass.push_back(mc); // ...and somewhere else to clean up: MyClass* mc = &listofmyclass.pop_back(); delete mc; // or something similar.
...in which case you will have to delete all list entries yourself when you no longer need them. The list now only holds pointers to objects.
i'm not talking about a list of pointers but a list of objects. so no new or delete.
i was wondering if this would work: pointer=& (*iteratorformylist)
Do the easy thing of first storing the created value in a local pointer, then push back the local pointer's value:
MyClass *obj = new MyClass(); objList.push_back(obj);
i was wondering if this would work: pointer=& (*iteratorformylist)
It should. The reason mypointer=&mylist.begin(); doesn't work is because begin() is an iterator, not an element. mypointer=&mylist.first() should work.
It should. The reason mypointer=&mylist.begin(); doesn't work is because begin() is an iterator, not an element. mypointer=&mylist.first() should work.
The function is front(), not first().
Yes, well, uh ... LOOK BEHIND YOU! A THREE-HEADED MONKEY!
where?
someone said that list.push_back() is invalid.
so i have to call at last list.push_back(myclass()); ??
Yes - you can't push nothing onto a list. You need to make an object and push it.