提问人:SPlatten 提问时间:9/8/2020 更新时间:9/8/2020 访问量:149
将具有算术的升压占位符转换为 std
Conversion of boost placeholders with arithmetic to std
问:
我正在努力转换一个C++项目,该项目使用提升和占位符来转换地图,现有逻辑是:
inline const std::vector<uint32_t> average(const std::pair<uint16_t, std::vector<uint32_t> >& left,
const std::pair<uint16_t, std::vector<uint32_t> >& right)
{
// Ejector rates should be symmetrical
assert(left.second.size() == right.second.size());
std::vector<uint32_t> result;
result.reserve(left.second.size());
namespace bl = boost::lambda;
// Walk both, do funny thing with each element in turn. Stuff into result.
std::transform(left.second.begin(), left.second.end(), right.second.begin(), std::back_inserter(result), (bl::_1 + bl::_2) / 2);
return result;
}
我想用 std 替换升压引用:
inline const std::vector<uint32_t> average(const std::pair<uint16_t, std::vector<uint32_t> >& left,
const std::pair<uint16_t, std::vector<uint32_t> >& right)
{
// Ejector rates should be symmetrical
assert(left.second.size() == right.second.size());
std::vector<uint32_t> result;
result.reserve(left.second.size());
namespace bl = boost::lambda;
// Walk both, do funny thing with each element in turn. Stuff into result.
std::transform(left.second.begin(), left.second.end(), right.second.begin(), std::back_inserter(result),
(std::placeholders::_1 + std::placeholders::_2) / 2);
return result;
}
我得到:
error C2784: 'std::_Deque_const_iterator<_Mydeque> std::operator +(_Deque_const_iterator<_Mydeque>::difference_type,std::_Deque_const_iterator<_Mydeque>)' : could not deduce template argument for 'std::_Deque_const_iterator<_Mydeque>' from 'std::_Ph<2>'
1> c:\program files (x86)\microsoft visual studio 12.0\vc\include\deque(555) : see declaration of 'std::operator +'
在包含以下内容的行上:
(std::placeholders::_1 + std::placeholders::_2) / 2);
正确的方法是什么?
答:
1赞
super
9/8/2020
#1
使用 lambda。
std::transform(left.second.begin(), left.second.end(), right.second.begin(), std::back_inserter(result),
[](auto a, auto b){ return (a + b) / 2; });
0赞
Vasilij
9/8/2020
#2
只需使用 lambda。
在一般情况下,您可以使用以下方法来避免处理参数:const auto refs
std::transform(left.second.begin(), left.second.end(), right.second.begin(), std::back_inserter(result), [] (auto const &a, auto const &b) { return (a+b)/2; });
对于像这样的小数值类型,您可以按值传递它们并仅使用或显式指定类型:int
const auto
std::transform(left.second.begin(), left.second.end(), right.second.begin(), std::back_inserter(result), [] (uint32_t a, uint32_t b) { return (a+b)/2; });
评论
0赞
Vasilij
9/8/2020
是的,谢谢!已经在编辑我的答案以显示这种情况))) 但是多亏了您的评论,我重新检查并编辑了一些模棱两可的术语。
评论
[&](uint32_t const lhs, uint32_t const rhs) { return (lhs + rhs) / 2; }