卓越飞翔博客卓越飞翔博客

卓越飞翔 - 您值得收藏的技术分享站
技术文章56205本站已运行405

c++ 数组长度怎么获取

在 c++ 中,获取数组长度的方法有:使用 sizeof 运算符除以元素大小。使用 std::array::size() 方法。使用指针操作,将数组名转换为指针,计算指针和数组末尾的差除以元素大小。

c++ 数组长度怎么获取

如何获取 C++ 数组的长度

在 C++ 中,数组的长度可以通过以下方法获取:

1. 使用 sizeof 运算符

sizeof 运算符返回数组中元素的字节数,除以元素的大小,即可得到数组的长度。

int main() {
  int arr[] = {1, 2, 3, 4, 5};
  int length = sizeof(arr) / sizeof(int);
  cout <p><strong>2. 使用 array::size() 方法</strong></p><p>如果使用 C++11 及更高版本,可以使用 std::array 类型,它提供了一个 size() 方法返回数组的长度。</p><pre class="brush:php;toolbar:false">#include <array>

int main() {
  std::array<int> arr = {1, 2, 3, 4, 5};
  int length = arr.size();
  cout <p><strong>3. 使用指针操作</strong></p>
<p>数组名可以<a style="color:#f60; text-decoration:underline;" href="https://www.php.cn/zt/77300.html" target="_blank">隐式转换</a>为指向数组第一个元素的指针,指针和数组末尾之间的差除以元素的大小,即可得到数组的长度。</p>
<pre class="brush:php;toolbar:false">int main() {
  int arr[] = {1, 2, 3, 4, 5};
  int length = (&amp;arr[4] - &amp;arr[0]) / sizeof(int) + 1;
  cout 
卓越飞翔博客
上一篇: c++怎么连接数据库
下一篇: 返回列表
留言与评论(共有 0 条评论)
   
验证码:
隐藏边栏