RCPP - 没有匹配函数来调用 'transform'

RCPP - no matching function for call to 'transform'

我在 Mac 上使用 Rcpp 时遇到问题(在 Windows 上没有出现问题)。

这是导致错误的 C++ 代码。

#include <Rcpp.h>
using namespace Rcpp;

NumericVector vecpow(const IntegerVector base, const NumericVector exp) 
{
  NumericVector out(base.size());
  std::transform(base.begin(), base.end(), exp.begin(), out.begin(), ::pow);
  return out;
}

似乎没有什么太花哨或太复杂的东西。

当我尝试编译它时仍然出现以下错误:

na_ma.cpp:7:3: error: no matching function for call to 'transform' std::transform(base.begin(), base.end(), exp.begin(), out.begin(), ::pow); ^~~~~~~~~~~~~~

/Library/Developer/CommandLineTools/usr/include/c++/v1/algorithm:2028:1: note: candidate function template not viable: requires 4 arguments, but 5 were provided transform(_InputIterator __first, _InputIterator __last, _OutputIterator __result, _UnaryOperation __op) ^

我想知道如何解决这个问题。在寻找解决方案时,我提出了一些创建 Makevars 文件的建议 - 但这对我不起作用。

也很好,如果有人能向我解释为什么会出现此错误,因为我不明白。

这实际上是 C++ 编译器错误。编译器无法将 ::pow 与 BinaryOp 匹配,因此将其打包到 lambda 中。这对我有用

std::transform(base.cbegin(), base.cend(), exp.cbegin(), out.begin(), [](double a, double b) {return ::pow(a, b); });

如果 lambda 不可用,可以尝试制作一个仿函数(lambda 等效于,请检查 https://medium.com/@winwardo/c-lambdas-arent-magic-part-1-b56df2d92ad2, https://medium.com/@winwardo/c-lambdas-arent-magic-part-2-ce0b48934809)。沿线(未经测试的代码,我不在我的电脑旁)

struct pow_wrapper {
    public: double operator()(double a, double b) {
        return ::pow(a, b);
    }
};

那就试试

std::transform(base.cbegin(), base.cend(), exp.cbegin(), out.begin(), pow_wrapper());