我是使用RCPP的新手,并试图编写一些代码来实质上重新创建R中“外部”函数的特例。我必须使用字符串向量,第一个包含模式,第二个包含句子。我正在检查所有句子的所有模式,并尝试返回一个矩阵,该矩阵是每个句子中每个模式出现的次数。
我已经取得了一些进展(尽管我敢肯定我的代码会吓到你们中的一些人:]
#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'一起使用,但是我很困惑。
我是使用RCPP的新手,并试图编写一些代码来实质上重新创建R中“外部”函数的特例。我必须使用字符串向量,第一个包含模式,第二个包含模式...] >
您将变量xstrings
声明为字符串向量。
std::vector<std::string> xstrings(x.size());
编译器抱怨是因为您声明了一个可以容纳字符串(即txt)的向量,并试图将其初始化为字符串(即xstrings [i])。它可能还会抱怨该行: