c++ - 在 Rcpp 中的字符串类型之间转换时出错
问题描述
我是使用 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”一起工作,但我很难过。
解决方案
您将变量声明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
并尝试使用xstrings[i];
类型为 的对象对其进行初始化std;:string
。
标准容器 std;:vector 中没有这样的非显式构造函数。所以编译器发出错误。
相反,你可以写例如
std::vector< std::string > txt( 1, xstrings[i] );
推荐阅读
- java - 为什么我不能通过带有 FailoverAppender 的 AsyncLogger/AsyncAppender 向 kafka 发送消息?
- python-3.x - 在可视化代码 jupyter 环境中运行时,Pandas 列名从索引列开始
- azure-functions - 将 OpenIdConnect 与 AzureFunctions 一起使用
- graphql - Vue graphql 中的错误:结果中缺少查询属性
- sql - Oracle 7 EXECUTE IMMEDIATE 替代方案
- reactjs - Recharts - 在 BarCharts 中设置没有轴的域
- arduino - 为 MKR 1500 获取额外的 UART 端口
- ios - “Calendar.current.isDate”日期参数是否需要使用同一时区的日期?
- scheme - Lisp/Scheme 中的引号与字符串相同吗?
- php - PHPMailer 不接受 docx mime 类型