C++ 数组长度如何计算
计算数组长度的方法
C++ 中数组长度可以通过以下方法计算:
使用 sizeof() 运算符:<code class="cpp">size_t length = sizeof(array) / sizeof(array[0]);</code>使用 .size() 方法(对于 vector):
<code class="cpp">size_t length = my_vector.size();</code>
示例
立即学习“C++免费学习笔记(深入)”;
<code class="cpp">// 声明一个包含 10 个整数的数组 int my_array[10]; // 计算数组长度 size_t length = sizeof(my_array) / sizeof(int); // 输出数组长度 cout << "数组长度:" << length << endl;</code>
输出:
<code>数组长度:10</code>
