如何在C++中获取动态数组的大小

eve*_*een 17 c++ dynamic-arrays

通过输入大小并将其存储到"n"变量中的动态数组代码,但我想从模板方法获取数组长度而不使用"n".

int* a = NULL;   // Pointer to int, initialize to nothing.
int n;           // Size needed for array
cin >> n;        // Read in the size
a = new int[n];  // Allocate n ints and save ptr in a.
for (int i=0; i<n; i++) {
    a[i] = 0;    // Initialize all elements to zero.
}
. . .  // Use a as a normal array
delete [] a;  // When done, free memory pointed to by a.
a = NULL;     // Clear a to prevent using invalid memory reference.
Run Code Online (Sandbox Code Playgroud)

此代码类似,但使用动态数组:

#include <cstddef>
#include <iostream>
template< typename T, std::size_t N > inline
std::size_t size( T(&)[N] ) { return N ; }
int main()
{
     int a[] = { 0, 1, 2, 3, 4, 5, 6 };
     const void* b[] = { a, a+1, a+2, a+3 };
     std::cout << size(a) << '\t' << size(b) << '\n' ;
}
Run Code Online (Sandbox Code Playgroud)

Rei*_*ica 36

你不能.分配的数组的大小new[]不以任何可以访问的方式存储.请注意,返回类型new []不是数组 - 它是一个指针(指向数组的第一个元素).因此,如果您需要知道动态数组的长度,则必须单独存储它.

当然,这样做的正确方法是避免new[]和使用std::vector替代方法,它会为您存储长度,并且启动异常安全.

这里是你的代码是什么样子使用std::vector,而不是new[]:

size_t n;        // Size needed for array - size_t is the proper type for that
cin >> n;        // Read in the size
std::vector<int> a(n, 0);  // Create vector of n elements initialised to 0
. . .  // Use a as a normal array
// Its size can be obtained by a.size()
// If you need access to the underlying array (for C APIs, for example), use a.data()

// Note: no need to deallocate anything manually here
Run Code Online (Sandbox Code Playgroud)

  • 不确定我理解为什么这个被低估了.其实,我相信我不... (3认同)
  • 你可以这样说:你在C++中拼写"动态数组"的方式是`std :: vector`,_ not_`T*array = new T []`.人们不能强调,没有理由使用新的数组(或者至少几乎没有 - 但我已经使用C++超过20年了,而且我从未发现过一个新的数组是适当). (3认同)
  • 我观察到在没有充分理由拒绝投票和没有评论/建议改善/修正答案之间存在很强的相关性。 (2认同)