【问题标题】:convert Rcpp::CharacterVector to std::string将 Rcpp::CharacterVector 转换为 std::string
【发布时间】:2011-12-07 19:25:47
【问题描述】:

我正在尝试在 Rcpp 函数中打开文件,因此我需要将文件名作为 char* 或 std::string。

到目前为止,我已经尝试了以下方法:

#include <Rcpp.h>
#include <boost/algorithm/string.hpp>
#include <fstream>
#include <string>

RcppExport SEXP readData(SEXP f1) {
    Rcpp::CharacterVector ff(f1);
    std::string fname = Rcpp::as(ff);
    std::ifstream fi;
    fi.open(fname.c_str(),std::ios::in);
    std::string line;
    fi >> line;
    Rcpp::CharacterVector rline = Rcpp::wrap(line);
    return rline;
}

但显然,as 不适用于 Rcpp::CharacterVector,因为我收到编译时错误。

foo.cpp: In function 'SEXPREC* readData(SEXPREC*)':
foo.cpp:8: error: no matching function for call to 'as(Rcpp::CharacterVector&)'
make: *** [foo.o] Error 1

有没有一种简单的方法可以从参数中获取字符串或以某种方式从 Rcpp 函数参数中打开文件?

【问题讨论】:

  • Rcpp::as(ff) 有效吗?
  • @IanFellows,是的,这行得通!

标签: c++ r rcpp


【解决方案1】:

Rcpp::as() 需要 SEXP 作为输入,而不是 Rcpp::CharacterVector。尝试将f1 参数直接传递给Rcpp::as(),例如:

std::string fname = Rcpp::as(f1); 

或者:

std::string fname = Rcpp::as<std::string>(f1); 

【讨论】:

  • Rcpp::as&lt;std::string&gt; 可与SEXPRcpp::CharacterVector 一起使用
【解决方案2】:

真正的问题是Rcpp::as 要求您手动指定要转换为的类型,例如Rcpp::as&lt;std::string&gt;

所有as 重载的输入始终是SEXP,因此编译器不知道使用哪一个,也无法自动做出决定。这就是为什么你需要帮助它。 wrap 的工作方式不同,它可以使用输入类型来决定它将使用哪个重载。

【讨论】:

    猜你喜欢
    • 2016-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多