gpt4 book ai didi

c++ - while (数组末尾) - 如何识别

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:53:08 25 4
gpt4 key购买 nike

我有一个数字数组 {1,2,3,4,5} 或一个字符数组或其他什么。我想写一个模板方法来打印出完整的数组。它有效,只是有一些问题。也许我先发布代码:

template <typename A>
void printArray(A start) {
int i = 0;
while (start[i] != 0) {
std::cout << start[i] << std::endl;
i++;
}
}

int main(int argc, char **argv) {

using namespace std;
int xs[] = {1,2,3,4,5,6,7}; //works
//int xs[] = {1,0,3,6,7}; of course its not working (because of the 0)
int *start = xs;

printArray(start);

return 0;
}

你能看出问题所在吗? while(start[i] != 0) 不是读取数组以结束的最佳方式 ;) 我还有其他选择吗?

谢谢!

最佳答案

方案一:传递指针和元素个数

 template<class T>
void doSth(T* arr, int size)

Upside - 适用于动态和自动阵列。
缺点 - 您必须知道尺寸。你必须通过它。

选项 2: 使用将自动推导的大小参数化模板

template <class T, int N>
void doSth(T(&arr)[N])

缺点 - 无法传递动态数组

选项 3: 成为一名优秀的程序员并使用 std::vector

关于c++ - while (数组末尾) - 如何识别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6816669/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com