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

标签 c++ r rcpp

我在 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-b56df2d92ad2https://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());

关于c++ - RCPP - 没有匹配函数调用 'transform',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56260846/

相关文章:

r - twitteR 在输入 twitter API PIN 后抛出 Forbidden 错误

r - 由RcppArmadillo.package.skeleton创建的NAMESPACE选项导致错误

r - 如何将用户定义的数据 C 结构用于 R 包

c++ - 为什么我不能在同一个代码行中创建和打开一个 ofstream?

r - 如何将reshape2包中的melt.data.frame函数返回 "variable"列更改为 "character"类?

c++ - 支持管道(一个有用的 Hello World)

r - 将数据帧的元素转换为二进制数据

Rcpp 和 int64 NA 值

c++ - 在 Qt 中抓取应用程序外的键盘事件

C++函数编码