在C++中返回生成的数组

Return a generated array in C++

本文关键字:数组 返回 C++      更新时间:2023-10-16

你们中的许多人可能认为这是一个已回答的问题,但我的情况有所不同//becouse 我在函数中声明数组//。问题是:我想做一个字符串拆分器,它将字符串分成块,这些块将成为数组的一部分。基本源代码为:

string separate(string str, int chunk, string mode = "res2end"){
int strlen = str.length();
int full = strlen / chunk;
int arr_size = full+1;
string result[arr_size]; //this is the 25th row
int modf = strlen % chunk;
    for(unsigned i=0; i<full; i++){
        int msr = i*chunk;
        int sp = msr - chunk;
        string subres = str.substr(msr, chunk);
        result[i] = subres;
    }
    if(modf != 0){
        int restm = strlen - (full * chunk);
        result[full+1] = str.substr(restm, modf);
    }
return result;
}

如您所见,我试图设置数组的长度,但什么都没有!出现一条错误消息:

..fc.h(25) : error C2057: expected constant expression
..fc.h(25) : error C2466: cannot allocate an array of constant size 0
..fc.h(25) : error C2133: 'result' : unknown size

因此,如果有人与我分享解决方案,我将非常高兴!

可变长度数组(VLA)不是C++标准的一部分(还?

您应该使用动态分配的数组,最好的选择是 std::vector 。这也将使您能够完全返回数组,因为您也不能从函数返回原始数组(或将数组传递给函数)。也介意更改返回类型。

std::vector< string > separate(string str, size_t chunk, string mode = "res2end"){
    size_t strlen = str.length();
    size_t full = strlen / chunk;
    std::vector< string > result; //this is the 25th row
    int modf = strlen % chunk;
    for(size_t i=0; i<full; i++){
        int msr = i*chunk;
        int sp = msr - chunk;
        result.push_back( str.substr(msr, chunk));
    }
    if(modf){
        int restm = strlen - (full * chunk);
        result.push_back( str.substr(restm, modf) );
    }
    return result;  // This could be a costly copy if prior to move introduced in C++11
}

您正在创建字符串数组,而不是单个字符串。您的函数返回单个字符串,但"result"变量是一个数组。