I’m trying to build a list inside a class in C++ and I don’t understand what I’m doing wrong
class Car(){
public:
Car();
~Car();
list <Objects> myList; //a list of some objects from one of my classes
list <Objects>::iterator it;
void addObject(Object obj);
void removeObject(Object obj);
};
Car::Car(){
//what do I need to add to initialize the list
it = myList.begin();
};
void addObject(Object obj){
//myList.insert(it, obj);
myList.push_back(obj);
}
void removeObject(Object obj){
myList.remove(obj);
}
I don’t get any build errors, however the debugger shouts at me “Expression: list insert iterator outside range”. I believe I’m not initializing the list inside my constructor and that’s the reason why. How can I do it?
Thanks
Everything is sorted now with inserting, however I’m having problems removing from the same list.
I presume it has to do with these “lovely” pointers. To get this once and for good, in my main I’m creating an object of type Car. Then I create some objects of type Object. Then I add them to my Car object using the above code. Why can’t I remove them? And most important: how many instances of the same object did I create using this code:
int main(){
Car myCar = Car();
Object one = Object("first object");
Object two = Object("second object");
Car.addObject(one);
Car.addObject(two);
Car.removeObject(one); //doesn't work???
}
Could someone please explain to me what am I doing wrong? Does anything have to do with my passing objects by value? What is the correct way in doing the above?
Thank you.
Your list will be initialised automatically in your constructor and you don’t need an iterator as a class member. To add your object to the list you should just call push_back:
See http://www.cplusplus.com/reference/stl/list/push_back/
To insert at a specific location see: http://www.cplusplus.com/reference/stl/list/insert/
If you are going to arbritrarily decide where to insert your new object then you will need to determine where each time using find(), if you were going to always insert at beginning or end then it’s easy enough to call