gpt4 book ai didi

string - 对Rcpp中的字符串串联感到困惑

转载 作者:行者123 更新时间:2023-12-02 09:05:27 25 4
gpt4 key购买 nike

我正在尝试遍历数据帧并连接由Rcpp中的空格分隔的字块。

我尝试阅读有关堆栈溢出的一些答案,但我对如何在Rcpp中连接字符串感到非常困惑。 (例如Concatenate StringVector with Rcpp)

我知道在C++中,您可以仅使用+运算符添加字符串。

这是我下面的Rcpp函数

cppFunction('
Rcpp::StringVector formTextBlocks(DataFrame frame) {
#include <string>
using namespace Rcpp;
NumericVector frame_x = as<NumericVector>(frame["x"]);

LogicalVector space = as<LogicalVector>(frame["space"]);
Rcpp::StringVector text=as<StringVector>(frame["text"]);
if (text.size() == 0) {
return text;
}
int dfSize = text.size();

for(int i = 0; i < dfSize; ++i) {
if ( i !=dfSize ) {
if (space[i]==true) {

text[i]=text[i] + text[i+1] ;

}
}

}
return text;
}
')

错误出现在 error: no match for 'operator+'的行上

字符串如何在循环内串联?

最佳答案

由于operator+是为std::string定义的,因此最简单的方法是将text列转换为std::vector<std::string>而不是Rcpp::StringVector来使用它:

Rcpp::cppFunction('
std::vector<std::string> formTextBlocks(DataFrame frame) {
LogicalVector space = as<LogicalVector>(frame["space"]);
std::vector<std::string> text=as<std::vector<std::string>>(frame["text"]);
if (text.size() == 0) {
return text;
}
int dfSize = text.size();

for(int i = 0; i < dfSize - 1; ++i) {
if (space[i]==true) {
text[i]=text[i] + text[i+1];
}
}
return text;
}
')

set.seed(20191129)
textBlock <- data.frame(space = sample(c(TRUE, FALSE), 100, replace = TRUE),
text = sample(LETTERS, 100, replace = TRUE),
stringsAsFactors = FALSE)
formTextBlocks(textBlock)
#> [1] "B" "N" "G" "BM" "M" "O" "C" "F" "OQ" "Q" "FH" "H" "D" "HK" "KH"
#> [16] "H" "S" "LX" "XO" "OY" "Y" "E" "VD" "D" "TN" "N" "LL" "LQ" "Q" "F"
#> [31] "XX" "X" "S" "R" "P" "L" "M" "GK" "KD" "DD" "D" "H" "M" "M" "K"
#> [46] "N" "GP" "PG" "G" "P" "G" "O" "N" "NY" "Y" "OX" "X" "LX" "XF" "FS"
#> [61] "SE" "E" "PS" "S" "YD" "D" "F" "Z" "H" "ZN" "N" "OM" "M" "XH" "HV"
#> [76] "V" "OX" "X" "J" "BZ" "Z" "FZ" "ZE" "E" "SV" "V" "G" "F" "DZ" "ZF"
#> [91] "F" "PB" "B" "K" "N" "U" "B" "PV" "V" "C"

reprex package(v0.3.0)创建于2019-11-29

笔记:
  • 我已经删除了#includeusing。这些不是必需的,并且不属于函数定义内。
  • 我已经删除了i != dfSize测试,无论如何它永远不会是false
  • ,因为您正在接触i+1元素,所以循环的长度减少了一个。
  • 关于string - 对Rcpp中的字符串串联感到困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59096720/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com