while(数组末尾)-如何识别
我有一个数字数组 {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)
不是读取数组结束的最佳方式;)我还有什么其他选择?
谢谢你!
I have an array of numbers {1,2,3,4,5} or an array of chars or whatever. I want to a write a template method to print out the full array. It works, there are just some problems. Maybe i post first the code:
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;
}
Can you see the problem? while(start[i] != 0)
is not the best way to read an array to end ;) What do I have for other options?
Thank you!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
选项 1: 传递指针和元素数量
Upside - 适用于动态数组和自动数组。
缺点 - 您必须知道尺寸。你必须通过它。
选项2:使用自动推导出的大小参数化模板
缺点 - 动态数组无法传递
选项3 : 成为一名优秀的程序员并使用
std::vector
Option 1: pass a pointer and the number of elements
Upside - will work with both dynamic and automatic arrays.
Downside - you must know the size. You must pass it.
Option2: parametrize the template with the size which will be auto-deduced
Downside - Dynamic arrays cannot be passed
Option 3: Be a good programmer and use
std::vector
's由于您使用的是 C++,因此从长远来看,
vector
和iterators
会给您带来更好的效果。Since you are using C++, a
vector<int>
anditerators
will do you better over the long haul.如果您想使用数组而不是指针,那么您可以将函数模板编写为:
因此更好的解决方案是:
std::vector
。或者甚至更好地使用范围(迭代器对),这是非常惯用的,因为:
printArray
现在可以与std::vector还有:
If you want to use array, not pointer, then you can write the function template as:
So better solution would be :
std::vector<T>
.Or even better use range (pair of iterators) which is very idiomatic, as:
printArray
now can be use withstd::vector<T>
also:传递数组的地址及其长度。
Pass both the address of array and its length.
如果您使用的是编译时数组,则可以使用模板来执行此操作:
如果您需要的只是打印数组,还请查看漂亮的打印机,它在内部使用这种东西。
If you are using a compile-time array, you can do this with a template:
If all you need is to print arrays, also check out the pretty printer, which uses this sort of stuff internally.