在C++中返回生成的数组
Return a generated array in C++
你们中的许多人可能认为这是一个已回答的问题,但我的情况有所不同//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"变量是一个数组。
相关文章:
- 为什么 C++ 中的字符数组返回其项目而不是地址?
- C++ bool 数组返回 1 或 0 以外的值
- C++ ostream 从对象数组返回数据
- 类中的重载运算符 [],因此它可以从模板类中的数组返回对象
- 指向对象的指针数组返回jibberish
- 具有基本结构的结构数组返回错误的答案
- 数组返回乐趣 movie_check()
- C++从字符数组返回类型为T的指针
- C++-将数组返回到主函数,并将数组传递给另一个函数
- C++:如何通过异常处理从越界数组返回值
- 整数数组返回类型
- 从字符串流复制到 char * 数组返回为函数参数
- C++函数从对象数组返回对象的副本.这是默认行为吗?
- 8字节数组返回长(C#到C++)
- 向c#数组返回一个字符数组c++
- 从并行数组返回值,并在以后的函数中使用这些值
- 将c++中的浮点数数组返回给Python
- 如何在gsoap中使字符串数组返回值
- 将两个字符相乘并向数组返回int
- C++套接字 - 从结构数组返回单个地址信息