我有以下代码。
最后的for循环应该遍历CCarList类的对象,打印出Car结构的a_rz和vin,并在AtEnd()方法返回true时停止。
但它并没有停止,而且当我试图达到a_rz和vin的值时,它会给出分段错误。
有人可以解释如何在我的CCarList类中使用正确的迭代器吗?
谢谢
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 it = 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;
a = 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);
for ( ; ! list_of_cars . AtEnd (); list_of_cars . Next () )
cout << list_of_cars . RZ () << ", " << list_of_cars . VIN () << endl;
return 0;
}
答案 0 :(得分:0)
您的问题是每个it
后迭代器push_back
没有更新/无效。在最后一次插入之后,它仍指向&#34;没有&#34;从一开始就是这样。
Soultion很简单 - 更新你的迭代器。添加添加新元素的方法:
void CCarList::Add(Car* car)
{
vCar.push_back(car);
it = vCar.begin();
}
然后只是:
list_of_cars.Add(a);
list_of_cars.Add(b);
list_of_cars.Add(c);
同样针对上述问题,您尝试打包vector
并提供vector
已提供的相同功能。考虑在该结构内移动与Car
结构相关的功能。仅在CCarList
中留下与CCarList
相关的方法。只需要一小段代码就可以向您展示我的意思:
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;
a = 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;
}