用二维字符数组的内容填充字符串的C ++向量:大小太大时失败

问题描述 投票:1回答:1

我是C ++编程的新手,正在尝试编写要从R运行的函数(使用RCpp)。

在函数中,我构造了一个以空值结尾的字符串的C数组。

该函数应该返回一个std :: vector,所以我尝试用字符串数组的内容“填充” std :: vector。这将起作用(并提供预期的输出),直到字符串数组超过一定大小(大约一百万)为止;任何较大的函数都会在运行时崩溃。为什么?

似乎甚至没有必要'填充'整个std :: vector-仅填充导致崩溃的第一个元素就足够了。但是,如果我用常量字符串(而不是字符串数组)填充第一个元素,则不会发生这种情况,该函数将愉快地创建并返回更大的std :: vectors(例如,一亿个字符串)。

这是一个最小的示例(我使用Rcpp从R编译并运行):

std::vector<std::string> test_function(int vecsize) {
    const char mystring[] = "will I crash or not?";
    char mychararray[ vecsize ][ sizeof(mystring) ];
    int i; for (i=0; i<sizeof(mystring); i++) {
        mychararray[0][i] = mystring[i];
    }
    std::vector<std::string> out_string(vecsize);
    out_string[0]=mychararray[0]; // this line causes crash when vecsize = 500000 or more
    // out_string[0]="like this I dont crash"; // but runs fine using this line instead with vecsize over 100 million
    return out_string;
}

调用test_function(100000)很好,但是调用test_function(1000000)会崩溃。

我认为这是一件很琐碎的事:在此先感谢您提出的任何建议或解释,我做错了什么。

c++ rcpp
1个回答
0
投票
在R中,字符变量也不同,并且它们的向量与数字向量也不同。但是Rcpp仍然使使用它们变得容易。

下面是处理字符变量矩阵的简单示例。

代码

#include <Rcpp.h> // [[Rcpp::export]] Rcpp::CharacterMatrix foo(Rcpp::CharacterMatrix x) { for (int i=0; i<x.rows(); i++) { for (int j=0; j<x.cols(); j++) { std::string s(x(i,j)); s[0] = std::toupper(s[0]); x(i,j) = s; } } return x; } /*** R foo(matrix(c("the","quick","brown","fox"),2,2)) */

输出

R> Rcpp::sourceCpp("~/git/stackoverflow/61508511/answer.cpp")

R> foo(matrix(c("the","quick","brown","fox"),2,2))
     [,1]    [,2]   
[1,] "The"   "Brown"
[2,] "Quick" "Fox"  
R> 
© www.soinside.com 2019 - 2024. All rights reserved.