我有一个基类,有几个类扩展它。我有一些通用库实用程序创建一个包含指向基类的指针的向量,以便任何子类都可以工作。我如何将矢量的所有元素转换为特定的子类?我可以将std :: vector <Animal*>转换为std :: vector <Dog*>而不必查看每个元素?
// A method is called that assumes that a vector containing
// Dogs casted to Animal is passed.
void myDogCallback(vector<Animal*> &animals) {
// I want to cast all of the elements of animals to
// be dogs.
vector<Dog*> dogs = castAsDogs(animals);
}
我天真的解决方案将是这个样子:书面会放了一堆空指针到您的狗矢量当动物载体含有其它动物的专业化
// A method is called that assumes that a vector containing
// Dogs casted to Animal is passed.
void myDogCallback(vector<Animal*> &animals) {
// I want to cast all of the elements of animals to
// be dogs.
vector<Dog*> dogs;
vector<Animal*>::iterator iter;
for (iter = animals.begin(); iter != animals.end(); ++iter) {
dogs.push_back(dynamic_cast<Dog*>(*iter));
}
}
重复:http://stackoverflow.com/questions/902667/stl-container-assignment-和 - 常量指针 – GManNickG 2009-07-24 03:39:32
这是不是很愚蠢 - 请注意,他不是从`矢量`复制到`矢量 `,但反过来! –
2009-07-24 03:45:21