如何在C ++中知道数组包含多少个元素? [英] How can I know in C++ how many elements an array contains?

查看:496
本文介绍了如何在C ++中知道数组包含多少个元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我有一个包含3个元素的数组

For example, I have an array with 3 elements

int array [] = {1, 4, 66};

我怎么知道array包含多少个元素?

How can I know how many elements array contains?

推荐答案

请执行以下操作:

std::size(myarray);

std::size <iterator>中.

某些资料来源会告诉您使用sizeof(myarray)/sizeof(myarray[0])之类的技巧".但这容易出错.数组的名称确实很容易衰减为指针,对此技巧"给出的结果是错误的. std::size将起作用或破坏构建.

Some sources will tell you to use a "trick" like sizeof(myarray)/sizeof(myarray[0]). But this is error-prone. The name of an array decays really easily to a pointer, for which this "trick" gives the wrong result. std::size will either work, or break the build.

此外,当您从C数组切换到std::array时,它仍然可以工作

Plus, when you switch from C arrays to std::array, it'll still work!

这篇关于如何在C ++中知道数组包含多少个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆