问题描述
通过输入大小并将其存储到n变量中,但是我想从模板方法获取数组长度而不使用n,动态数组的代码。
int * a = NULL; // Pointer to int,initialize to nothing。
int n; //数组所需的大小
cin>> n; //读入大小
a = new int [n]; //分配n整数并将ptr保存在a中。
for(int i = 0; i a [i] = 0; //将所有元素初始化为零。
}
。 。 。 //使用a作为正常数组
delete [] a; //完成后,a指向的可用内存。
a = NULL; //清除a以防止使用无效的内存引用。
此代码类似,但使用动态数组:
#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<<尺寸(a) '\t'<<尺寸(b) '\\\
';
}
分配有 new []
的数组的大小不以任何可以被访问的方式存储。注意, new []
的返回类型不是数组 - 它是一个指针(指向数组的第一个元素)。所以如果你需要知道动态数组的长度,你必须单独存储它。
当然,正确的方法是避免 new []
并使用 std :: vector
来存储长度,并且异常安全启动。
这里是你的代码看起来像使用 std :: vector
而不是 new []
:
size_t n; // array所需的大小 - size_t是适当的类型
cin>> n; //读入大小
std :: vector< int> a(n,0); //创建n个元素的向量,初始化为0
。 。 。 //使用a作为一个普通的数组
//它的大小可以通过a.size()获得
//如果你需要访问底层数组(例如C API),使用.data()
//注意:此处不需要手动释放
Code for dynamic array by entering size and storing it into "n" variable, but I want to get the array length from a template method and not using "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.
This code is similar, but using a dynamic array:
#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' ;
}
You can't. The size of an array allocated with new[]
is not stored in any way in which it can be accessed. Note that the return type of new []
is not an array - it is a pointer (pointing to the array's first element). So if you need to know a dynamic array's length, you have to store it separately.
Of course, the proper way of doing this is avoiding new[]
and using a std::vector
instead, which stores the length for you and is exception-safe to boot.
Here is what your code would look like using std::vector
instead of 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
这篇关于如何获取C ++中的动态数组大小的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!