在容器中查找派生对象

Find derived objects in a container

本文关键字:派生 对象 查找      更新时间:2023-10-16

假设我有基类Thing,从中我有ShoesPantsShirt。然后我有一个vector<Thing*> closet.

如何找到我的closet中有多少Shirt

std::count_if与 lambda 一起使用,lambda 使用动态向下转换来确定每个元素是否指向一个Shirt(或其子类型 - 这也会捕获,例如,TShirt是继承Shirt的类的TShirt对象):

auto shirts = std::count_if(
std::begin(closet),
std::end(closet),
[] (Thing const *thing) {
return dynamic_cast<Shirt const *>(thing) != nullptr;
}
);