在 Rcpp 中的字符串类型之间转换时出错

Error converting between string types in Rcpp

本文关键字:之间 转换 出错 类型 字符串 Rcpp      更新时间:2023-10-16

我是使用 RCPP 的新手,并尝试编写一些代码,本质上是在 R 中重新创建"outer"函数的特殊情况。我必须字符串向量,第一个包含模式,第二个包含句子。我正在检查所有模式的所有句子,并尝试返回一个矩阵,该矩阵是每个模式在每个句子中出现的次数。

我已经取得了一些进展(尽管我相信你们中的一些人会被我的代码吓坏(:


#include <Rcpp.h>
#include <string.h>
#include <string>
#include <algorithm>
using namespace Rcpp;
// [[Rcpp::plugins("cpp11")]]
int addOccurrences(std::vector< std::string > &txt, std::vector< std::string > &pat) 
{ 
int M = pat.size(); 
int N = txt.size(); 
int res = 0; 
/* A loop to slide pat[] one by one */
for (int i = 0; i <= N - M; i++) 
{  
/* For current index i, check for  
pattern match */
int j; 
for (j = 0; j < M; j++) 
if (txt[i+j] != pat[j]) 
break; 
// if pat[0...M-1] = txt[i, i+1, ...i+M-1] 
if (j == M)   
{ 
res++; 
j = 0; 
} 
} 
return res; 

} 

//[[Rcpp::export]]
NumericMatrix freqMatrix (Rcpp::StringVector x,Rcpp::StringVector y)
{
Rcpp::NumericMatrix matrx(x.size(),y.size());
int i = 1;
int j = 1;

std::vector<std::string> xstrings(x.size());
int k;
for (k = 0; k < x.size(); k++){
xstrings[k] = x(k);
}
std::vector<std::string> ystrings(y.size());
int l;
for (l = 0; l < y.size(); l++){
ystrings[l] = y(l);
}


for(i = 1; i<=x.size(); i++)
{
std::vector< std::string > txt = xstrings[i];
for(j = 1; j<=y.size(); j++)
{
std::vector< std::string > pat = ystrings[j];
matrx(i,j) = addOccurrences(txt, pat);
j = j + 1;
}
i = i + 1;
}
return matrx;
}

我已经摆脱了大多数错误,但我被困在底部附近。我得到的错误说:

"conversion from '__gnu_cxx::__alloc_traits<std::allocator<std::basic_string<char> > >::value_type {aka std::basic_string<char>}' to non-scalar type 'std::vector<std::basic_string<char> >' requested
std::vector< std::string > txt = xstrings[i];"

我在第二次转换"ystrings[j]"时收到相同的错误

我已经尝试了几种不同的方法来让它与"std::vector"和"Rcpp::StringVector"一起使用,但我被难住了。

您将变量xstrings声明为字符串向量。

std::vector<std::string> xstrings(x.size());

然后在这个循环中,由于未知原因从 1 而不是 0 开始(当i等于x.size()时,它似乎可以调用未定义的行为(

for(i = 1; i<=x.size(); i++)
{
std::vector< std::string > txt = xstrings[i];
//

txt声明了另一个字符串向量,并尝试使用类型为std;:string的对象xstrings[i];对其进行初始化。

在标准容器 std;:vector 中没有这样的非显式构造函数。因此,编译器会发出错误。

相反,你可以写例如

std::vector< std::string > txt( 1,  xstrings[i] );

编译器抱怨是因为您声明了一个可以容纳字符串(即 .txt(的向量并尝试将其初始化为字符串(即 xstrings[i](。它可能还会抱怨这条线:

std::vector< std::string > pat = ystrings[j];

鉴于addOccurrences(...(检查单个句子的单个模式,它不应该将std::string类型的变量作为输入参数吗?这意味着它应该声明如下:

int addOccurrences(const std::string & txt, const std::string & pat) 
{
// do stuff...
}

然后,freqMatrix 中的最后一个循环可以写成:

for(i = 1; i<=x.size(); i++)
{
for(j = 1; j<=y.size(); j++)
{
matrx(i,j) = addOccurrences(xstrings[i], ystrings[j]);
}
}