【发布时间】:2011-10-12 14:23:40
【问题描述】:
我有一个数字数组 {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) 不是读取数组以结束的最佳方式;)我还有什么其他选择?
谢谢!
【问题讨论】:
-
你不是在传递一个数组,你是在传递一个指针。
-
不要将普通数组视为 C 风格的空终止数组。
标签: c++ arrays templates while-loop