将单个 Rcpp::IntegerVector 元素转换为字符 [英] Convert individual Rcpp::IntegerVector element to a character
问题描述
我必须将 Rcpp::IntegerVector 的各个元素转换为它们的字符串形式,以便我可以向它们添加另一个字符串.我的代码如下所示:
I have to convert individual elements of Rcpp::IntegerVector into their string form so I can add another string to them. My code looks like this:
#include <Rcpp.h>
using namespace Rcpp;
// [[Rcpp::export]]
Rcpp::String int_to_char_single_fun(int x){
// Obtain environment containing function
Rcpp::Environment base("package:base");
// Make function callable from C++
Rcpp::Function int_to_string = base["as.character"];
// Call the function and receive its list output
Rcpp::String res = int_to_string(Rcpp::_["x"] = x); // example of original param
// Return test object in list structure
return (res);
}
//[[Rcpp::export]]
Rcpp::CharacterVector add_chars_to_int(Rcpp::IntegerVector x){
int n = x.size();
Rcpp::CharacterVector BASEL_SEG(n);
for(int i = 0; i < n; i++){
BASEL_SEG[i] = "B0" + int_to_char_single_fun(x[i]);
}
return BASEL_SEG;
}
/*** R
int_vec <- as.integer(c(1,2,3,4,5))
BASEL_SEG_char <- add_chars_to_int(int_vec)
*/
我收到以下错误:
no match for 'operator+'(operand types are 'const char[3]' and 'Rcpp::String')
我无法导入任何 C++ 库(如 Boost)来执行此操作,并且只能使用 Rcpp 功能执行此操作.如何在 Rcpp 中将字符串添加到整数?
I cannot import any C++ libraries like Boost to do this and can only use Rcpp functionality to do this. How do I add string to integer here in Rcpp?
推荐答案
我们基本上在 Rcpp Gallery 当我们在 Boost 时a-second-boost-example/" rel="noreferrer">lexical_cast 的示例(尽管那个是相反的).所以重写它很快就会产生这个:
We basically covered this over at the Rcpp Gallery when we covered Boost in an example for lexical_cast (though that one went the other way). So rewriting it quickly yields this:
// We can now use the BH package
// [[Rcpp::depends(BH)]]
#include <Rcpp.h>
#include <boost/lexical_cast.hpp>
using namespace Rcpp;
using boost::lexical_cast;
using boost::bad_lexical_cast;
// [[Rcpp::export]]
std::vector<std::string> lexicalCast(std::vector<int> v) {
std::vector<std::string> res(v.size());
for (unsigned int i=0; i<v.size(); i++) {
try {
res[i] = lexical_cast<std::string>(v[i]);
} catch(bad_lexical_cast &) {
res[i] = "(failed)";
}
}
return res;
}
/*** R
lexicalCast(c(42L, 101L))
*/
输出
R> Rcpp::sourceCpp("/tmp/lexcast.cpp")
R> lexicalCast(c(42L, 101L))
[1] "42" "101"
R>
替代方案
因为将数字转换为字符串与计算本身一样古老,所以您也可以使用:
Alternatives
Because converting numbers to strings is as old as computing itself you could also use:
itoa()
snprintf()
- 流
- 可能还有一些我一直忘记.
这篇关于将单个 Rcpp::IntegerVector 元素转换为字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!