C++ iterator as class member used in class method -
i have following code.
the for-loop @ end should go through object of ccarlist class, print out the a_rz , vin of car structure , stop when atend() method returns true.
but doesnt stop , when try reach values of a_rz , vin gives segmentation fault.
could someone, please, explain how use iterator in ccarlist class?
thanks
typedef struct car { string a_rz; unsigned int vin; }car; class ccarlist { public: string rz ( void ) const; unsigned int vin ( void ) const; bool atend ( void ) const; void next ( void ); vector<car*> vcar; vector<car*>::const_iterator = vcar.begin(); public: ccarlist ( void ){} ~ccarlist ( void ){} }; string ccarlist::rz ( void ) const { return "ahoj"; //(**it).a_rz; } unsigned int ccarlist::vin ( void ) const{ return 5; //(**it).vin; } bool ccarlist::atend ( void ) const { if(it == vcar.end()) return true; return false; } void ccarlist::next ( void ){ it++; } int main() { car *a, *b, *c; = new car; b = new car; c = new car; (*a).a_rz = "abc"; (*a).vin = 45; (*b).a_rz = "dfg"; (*b).vin = 65; (*c).a_rz = "jkl"; (*c).vin = 23; ccarlist list_of_cars; list_of_cars.vcar.push_back(a); list_of_cars.vcar.push_back(b); list_of_cars.vcar.push_back(c); ( ; ! list_of_cars . atend (); list_of_cars . next () ) cout << list_of_cars . rz () << ", " << list_of_cars . vin () << endl; return 0; }
your problem iterator it
not being updated/invalidated after each push_back
. after last insertion still points "nothing" beginning.
soultion simple -- update iterator. add method adding new elements:
void ccarlist::add(car* car) { vcar.push_back(car); = vcar.begin(); }
and just:
list_of_cars.add(a); list_of_cars.add(b); list_of_cars.add(c);
also regarding above problem, you're trying wrap vector
, provide same functionality vector
already provides. consider moving functionality related car
structure inside structure. , leaving in ccarlist
methods related ccarlist
. short piece of code show mean:
typedef struct car { string a_rz; unsigned int vin; } car; class ccarlist { public: vector<car*> vcar; ccarlist(void){} ~ccarlist(void){} }; int main() { car *a, *b, *c; = new car; b = new car; c = new car; a->a_rz = "abc"; a->vin = 45; b->a_rz = "dfg"; a->vin = 65; c->a_rz = "jkl"; c->vin = 23; ccarlist list_of_cars; list_of_cars.vcar.push_back(a); list_of_cars.vcar.push_back(b); list_of_cars.vcar.push_back(c); for(auto car : list_of_cars.vcar) cout << car->a_rz << ", " << car->vin << endl; return 0; }
Comments
Post a Comment