在容器中查找派生对象

Hic*_*man 0 c++ oop vector

比方说,我有基类Thing和我有Shoes,Pants,Shirt.然后我有一个vector<Thing*> closet.

我怎么能找到Shirt我有closet多少?

cdh*_*wie 5

使用std::count_if与使用的λ 动态垂头丧气,以确定是否每一个元素指向一个Shirt(或它们的子类型-这也将赶上,比方说,TShirt对象,其中TShirt是继承的类Shirt):

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