需要获取数组的长度 [英] Need to get length of an array

查看:84
本文介绍了需要获取数组的长度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在变量len1和len2中获取数组长度的函数应该是什么,我无法通过函数length()来获取数组的长度,为什么?

What should be the function to get length of array in variables len1 and len2, i am not able to get the length of array through the function length() ,why is it?

#include<iostream.h>
#include<conio.h>

template <class X>
class MyClass 
{
void disparray(X *p,int n)
{
     int i;
     for(i=0;i<n;i++)>
            cout<<p[i]<<" ";
}

int main()
{
    int a[]={1,2,3,4};
    float b[]={1.1,2.2,3.3};
    int len1,len2;
    len1=a.length();
    len2=b.length();
    disparray(a,len1);
    disparray(b,len2);
    getch();
    return 0;
}

推荐答案

数组的长度在声明时设置.例如:

int a[10];
声明一个10个整数的数组.或:

int a[] = {1,2,3};
声明一个由3个int组成的数组,其中包含1个,2个和3个.

我认为您可能正在考虑CArray类,该类可以动态更改其大小.这是指向CArray的Microsoft帮助的链接:

http://msdn.microsoft.com/en-us/library/4h2f09ct (v = vs.80).aspx [
The length of an array is set when it is declared. For Example:

int a[10];
Declares an array of 10 ints. Or:

int a[] = {1,2,3};
Declares an array of 3 ints which contain 1, 2 and 3.

I think perhaps you are thinking of the class CArray, which can dynamically change its size. Here''s the link to the Microsoft help for CArray:

http://msdn.microsoft.com/en-us/library/4h2f09ct(v=vs.80).aspx[^]


我认为您需要返回C ++参考指南,了解简单类型与类/结构之间的区别.您定义的数组是简单类型,不具有类或结构所具有的成员函数.获得简单类型数组长度的唯一方法是使用sizeof运算符,但这在编译时已解决,因此可能不适合您的目的.您可能需要使用一种STL [模板 [ ^ ],因为您的规范不正确.

[edit]我还应该提到_countof()(在 stdlib.h 中定义),它给出的是元素数量而不是总大小.也是ARRAYSIZE(在 WinNT.h 中定义).[/edit]
I think you need to go back to your C++ reference guides and learn the difference between simple types and classes/structs. The arrays you have defined are simple types and do not have member functions in the way that classes or structs have. The only way to get the length of a simple type array is to use the sizeof operator, but this is resolved at compile time so will probably not suit your purpose. You probably need to use one of the STL classes[^] that handle collections, probably list or vector. You should also read up on the syntax of Templates[^], as your specification is incorrect.

[edit]I should also mention _countof() (defined in stdlib.h) which gives the number of elements rather than the total size. Also ARRAYSIZE (defined in WinNT.h).[/edit]


对于标准C ++数组,您可以使用它来查找它.元素数:
sizeof(arr)/sizeof(arr [0])
在这里,arr是您声明的数组.它基本上意味着总数组的大小除以每个元素的大小.
尽管我一般不建议采用这种方法.
For a standard C++ array you can use this to find out it''s number of elements:
sizeof(arr)/sizeof(arr[0])
Here, arr is the array you declared. It basically means the size of the total array divided by the size of each element.
Though I don''t suggest this approach in general.


这篇关于需要获取数组的长度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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