我正在编写一个接受字符串、字符串指针和 int 的函数。 该函数根据一组规则拆分字符串,并将每个标记放入一个数组中。我需要使用 int 变量中的元素数等从函数中返回数组。我对如何返回数组感到困惑,因为我不能使用 auto,否则它会被破坏,我不愿意使用 new 作为我觉得这是不完整的。
我对如何解决这个问题有其他想法,但想先看看其他人是如何解决这个问题的。我也可能是错的,并且可以将 auto 从数组中传递出去。我也不能使用 vector ,所以有一个复制构造函数。
Vector 不能使用,因为这是对我提出的挑战,我被要求不要使用模板。
最佳答案
考虑到这些限制,这更像是 C 问题而不是 C++ 问题。
返回数组的常见C模式实际上是让调用者传入一个数组来填充。这让调用者决定分配(并因此取消分配)。
你的函数原型(prototype)看起来像
int Function(string str1, string_ptr str2, int n, int* pOutArray, int cOutArray);
函数返回写入 pOutArray 的元素数。
在您处理 pOutArray 为 NULL 的实现中,在这种情况下,您只需计算元素的数量,然后返回它。这使您可以根据需要以多种方式之一调用该函数:-
int out[5]={0};
int cFilled = Function(s1,s2,x,out,_countof(out));
// Further code can use up to 5<cFilled elements from the array.
或者,
int cElt = Function(s1,s2,x,NULL,0);
int* pOut = malloc(sizeof(int)*cElt);
Function(s1,s2,x,pOut,cElt);
// pOut now contains exactly the number of elements extracted.
free(pOut);
关于c++数组传递困境,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2681890/