我有一个基类 fruit
和子类 oranges
和 apples
.两个子类都重载了 operator+
这样我就知道如何对橙子或苹果求和了。现在我有一个指向基类的引用 vector std::vector<std::reference_wrapper<fruit>>
我想知道该 vector 中存储了多少苹果和橙子,我该如何实现?
最佳答案
#include <vector>
#include <functional>
#include <typeinfo>
#include <algorithm>
struct fruit { virtual ~fruit() = default; };
struct apple : fruit {};
struct orange : fruit {};
auto count_oranges(std::vector<std::reference_wrapper<fruit>> const& vec) -> std::size_t
{
return std::count_if(begin(vec), end(vec), [](auto&& ref)
{
return typeid(ref.get()) == typeid(orange);
});
}
关于c++ - 仅当类型匹配时如何在 std::vector 上添加元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46493631/