仅当其类型匹配时,如何在std :: vector上添加元素
How to add elements on a std::vector only if their type matches
我有一个基类fruit
和子类oranges
和apples
。两个子类过载operator+
,因此我知道如何概括橙色或苹果。现在,我有一个对基类std::vector<std::reference_wrapper<fruit>>
的参考文献,我想知道该向量中存储了多少个苹果和橘子,我该如何实现?
#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);
});
}
相关文章:
- 使用std::vector的OpenCL矩阵乘法
- POCO::PostgreSQL:如何将std::vector支持添加到`Binder::bind`
- std::vector的包装器,使数组的结构看起来像结构的数组
- 编译器如何区分std::vector的构造函数
- 使用 pqxx 将 std::vector 存储在 postgresql 中,并从数据库中检索它
- 在std::vector上存储带有模板的类实例
- 在main()之外初始化std::vector会导致性能下降(多线程)
- 为什么std::vector比数组慢
- std::vector::迭代器是否可以合法地作为指针
- 如何将二进制格式的 C++ 对象的 std::vector 保存到磁盘?
- 为什么std::vector和std::valarray初始化构造函数不同
- ";结果类型必须是可从输入范围的值类型""构造的;创建std::vector时
- 在没有未定义行为的情况下实现类似std::vector的容器
- 如何调整 std::vector of Eigen::MatrixXd 的大小
- 使用 std::vector::reverse_iterator 将 int 序列化为字节向量?
- 如何将AERT_Allocate与 std:vector 一起使用
- 推导 std::vector::back() 的返回类型
- 如何将原始字节附加到 std::vector?
- std::vector 没有重载函数的实例与参数列表匹配
- 如果 KEY 是 std::list 或 std::vector 而不是值,那么 std::map 的默认行为是什么?