c++ - 容器有重新绑定吗?
问题描述
在 C++ 标准库allocators
中可以反弹。
std::allocator<int>::rebind<double>::other
给std::allocator<double>
.
有没有一种简单的方法可以用容器做到这一点?
原因是我有一个将容器元素乘以标量的函数。
template<class Container, typename S>
auto elementwise_multiply_by_scalar(Container const& c, S s){
Container ret(c.size());
for(auto& e : ret) e *= s;
return ret;
}
但如果e * s
与 不是同一类型e
,我想这样做:
template<class Container, typename S>
auto elementwise_multiply_by_scalar(Container const& c, S s){
Container::rebind<decltype(Container::value_type{}*s)> ret(c.size());
auto it2 = ret.begin();
for(auto it1 = c.begin(); it1 != c.end(); ++it1, ++it2) *it2 = s * *it1;
return ret;
}
(我想不清楚为什么我希望输出与输入是同一类容器,但我想这是预期的结果。)
我可以使用模板模板参数(如template<template<typename> class V>
),但它似乎也有问题。
我们需要某种东西container_traits<V>::rebind
吗?(例如container_traits<std::vector<double, myallocator<double> >>::rebind<int>::other
-> std::vector<int, myallocator<double>::rebind<int>::other>
)
解决方案
像这样的东西可能会起作用:
struct A
{
};
struct B
{
};
struct C
{
};
C operator *(const A&, const B&)
{
return C();
}
template <typename Container, typename ValueType>
struct ContainerConverter
{
};
template <typename SourceValueType, typename ValueType>
struct ContainerConverter<std::vector<SourceValueType>, ValueType>
{
typedef typename std::vector<ValueType> result_type;
};
template <typename Container, typename S>
auto mult(const Container& c, const S& s)
{
typedef typename Container::value_type source_element;
typedef decltype(c.front()*s) result_element;
typename ContainerConverter<Container, result_element>::result_type result;
std::transform(c.begin(), c.end(), std::back_inserter(result), [&](const source_element& e){ return e * s; } );
return result;
}
int main()
{
std::vector<A> a;
std::vector<C> c = mult(a, B());
}
您需要专门ContainerConverter
针对要支持的每种容器类型。
如果您的容器不全部支持,std::back_inserter
请参阅std::transform to absolute container。
推荐阅读
- ruby - 在ruby方法块中,如何获取分配给方法返回值的变量名
- java - 通过 pdfbox 从 pdf 文档中提取文本时没有 Unicode 映射错误,因为字体字典中缺少 ToUnicode CMap 条目
- javascript - Soundcloud JavaScript API 发表评论不起作用
- javascript - 如何使用 firebase 函数发送和获取数据?
- angular - 如何避免 Observable 中超出最大调用堆栈大小?
- javascript - 搜索功能(JAVASCRIPT)
- ios - 请从此设备中删除使用您的免费帐户签名的应用程序以保持在限制范围内
- javascript - vue js全局变量出错但工作
- html - 使网页在中小屏幕上响应
- python - 如何在odoo中为继承费用模块制作课程,请帮助我