代码之家  ›  专栏  ›  技术社区  ›  Maxpm

如何确定数组的长度?

  •  457
  • Maxpm  · 技术社区  · 15 年前

    有没有办法找到一个数组有多少个值?检测我是否到达数组的末尾也可以。

    25 回复  |  直到 14 年前
        1
  •  484
  •   Community Mohan Dere    6 年前

    如果您指的是C样式数组,则可以执行以下操作:

    int a[7];
    std::cout << "Length of array = " << (sizeof(a)/sizeof(*a)) << std::endl;
    

    这对指针不起作用(即 不会

    int *p = new int[7];
    std::cout << "Length of array = " << (sizeof(p)/sizeof(*p)) << std::endl;
    

    或:

    void func(int *p)
    {
        std::cout << "Length of array = " << (sizeof(p)/sizeof(*p)) << std::endl;
    }
    
    int a[7];
    func(a);
    

    在C++中,如果你想要这种行为,那么你应该使用容器类; std::vector .

        2
  •  134
  •   Motti    8 年前

    就像别人说的你可以用 sizeof(arr)/sizeof(*arr)

    template<class T, size_t N>
    constexpr size_t size(T (&)[N]) { return N; }
    

    这有一个很好的特性,即无法为非数组类型编译(visual studio有 _countof constexpr 使其成为编译时表达式,这样它就不会在宏上有任何缺点(至少我不知道)。

    你也可以考虑使用 std::array 从C++ 11公开它的长度,在本地C数组上没有开销。

    std::size() <iterator> 同样的头,也适用于STL容器(感谢 @Jon C

        3
  •  81
  •   MahlerFive    15 年前

    sizeof( myArray ) 将获取为该数组分配的总字节数。然后,可以通过除以数组中一个元素的大小来确定数组中元素的数量: sizeof( myArray[0] )

        4
  •  54
  •   Prasoon Saurav    15 年前

    对!

    尝试 sizeof(array)/sizeof(array[0])

    检测我是否到达数组的末尾也可以。

    除非你的数组是一个字符数组(即字符串),否则我看不出有什么办法。

    P.S:在C++中总是使用 std::vector . 有几个内置功能和一个扩展功能。

        5
  •  53
  •   Arnav Borborah    8 年前

    这是一个老问题,它值得更新C++ 17的答案。在标准库中现在有一个模板函数 std::size() ,它返回std容器或C样式数组中的元素数。例如:

    #include <iterator>
    
    uint32_t data[] = {10, 20, 30, 40};
    auto dataSize = std::size(data);
    // dataSize == 4
    
        6
  •  28
  •   eq-    15 年前

    std::vector 有办法 size() 它返回向量中的元素数。

        7
  •  26
  •   JukkaP    12 年前
    #include <iostream>
    
    int main ()
    {
        using namespace std;
        int arr[] = {2, 7, 1, 111};
        auto array_length = end(arr) - begin(arr);
        cout << "Length of array: " << array_length << endl;
    }
    
        8
  •  23
  •   Jaege    9 年前

    自从C++ 11以来,引入了一些新的模板来帮助减少处理数组长度时的痛苦。所有这些都在标题中定义 <type_traits>

    要得到多维数组的任意维的长度, decltype std::extent . 例如:

    #include <iostream>
    #include <type_traits> // std::remove_extent std::remove_all_extents std::rank std::extent
    
    template<class T, size_t N>
    constexpr size_t length(T(&)[N]) { return N; }
    
    template<class T, size_t N>
    constexpr size_t length2(T(&arr)[N]) { return sizeof(arr) / sizeof(*arr); }
    
    int main()
    {
        int a[5][4][3]{{{1,2,3}, {4,5,6}}, { }, {{7,8,9}}};
    
        // New way
        constexpr auto l1 = std::extent<decltype(a)>::value;     // 5
        constexpr auto l2 = std::extent<decltype(a), 1>::value;  // 4
        constexpr auto l3 = std::extent<decltype(a), 2>::value;  // 3
        constexpr auto l4 = std::extent<decltype(a), 3>::value;  // 0
    
        // Mixed way
        constexpr auto la = length(a);
        //constexpr auto lpa = length(*a);  // compile error
        //auto lpa = length(*a);  // get at runtime
        std::remove_extent<decltype(a)>::type pa;  // get at compile time
        //std::remove_reference<decltype(*a)>::type pa;  // same as above
        constexpr auto lpa = length(pa);
        std::cout << la << ' ' << lpa << '\n';
    
        // Old way
        constexpr auto la2 = sizeof(a) / sizeof(*a);
        constexpr auto lpa2 = sizeof(*a) / sizeof(**a);
        std::cout << la2 << ' ' << lpa2 << '\n';
    
        return 0;
    }
    

    BTY,要获取多维数组中的元素总数:

    constexpr auto l = sizeof(a) / sizeof(std::remove_all_extents<decltype(a)>::type);
    

    #include <iostream>
    #include <type_traits>
    
    
    template<class T>
    constexpr size_t len(T &a)
    {
        return sizeof(a) / sizeof(typename std::remove_all_extents<T>::type);
    }
    
    int main()
    {
        int a[5][4][3]{{{1,2,3}, {4,5,6}}, { }, {{7,8,9}}};
        constexpr auto ttt = len(a);
        int i;
        std::cout << ttt << ' ' << len(i) << '\n';
    
        return 0;
    }
    

    更多如何使用它们的例子可以通过以下链接找到。

        9
  •  18
  •   metal    9 年前

    还有Tr1/c++ 11 /c++ 17方式(见图) Live on Coliru

    const std::string s[3] = { "1"s, "2"s, "3"s };
    constexpr auto n       = std::extent<   decltype(s) >::value; // From <type_traits>
    constexpr auto n2      = std::extent_v< decltype(s) >;        // C++17 shorthand
    
    const auto     a    = std::array{ "1"s, "2"s, "3"s };   // C++17 class template arg deduction -- http://en.cppreference.com/w/cpp/language/class_template_argument_deduction
    constexpr auto size = std::tuple_size_v< decltype(a) >;
    
    std::cout << n << " " << n2 << " " << size << "\n"; // Prints 3 3 3
    
        10
  •  9
  •   Mr. Foots    12 年前

    而不是使用内置数组函数aka:

     int x[2] = {0,1,2};
    

    #include <array>
    array<type_of_the_array, number_of_elements_in_the_array> Name_of_Array = {};
    

    所以现在如果你想找到数组的长度,你需要做的就是在array类中使用size函数。

    Name_of_Array.size();
    

    它应该返回数组中元素的长度。

        11
  •  6
  •   Tarun Maganti    10 年前

    在C++中,使用STD::数组类声明数组,可以很容易地找到数组的大小,也可以找到最后一个元素。

    #include<iostream>
    #include<array>
    int main()
    {
        std::array<int,3> arr;
    
        //To find the size of the array
        std::cout<<arr.size()<<std::endl;
    
        //Accessing the last element
        auto it=arr.end();
        std::cout<<arr.back()<<"\t"<<arr[arr.size()-1]<<"\t"<<*(--it);
    
        return 0;
    }
    

    事实上,array类还有很多其他的函数可以让我们使用array作为标准容器。
    Reference 1 to C++ std::array class
    Reference 2 to std::array class
    参考文献中的例子很有帮助。

        12
  •  4
  •   Ito    7 年前

    int myArray[]={0,1,2,3,4,5,7};

    1) sizeof(<array>) / sizeof(<type>):

    std::cout << "Size:" << sizeof(myArray) / sizeof(int) << std::endl;
    

    2) sizeof(<array>) / sizeof(*<array>):

    std::cout << "Size:" << sizeof(myArray) / sizeof(*myArray) << std::endl;
    

    3) sizeof(<array>) / sizeof(<array>[<element>]):

    std::cout << "Size:" << sizeof(myArray) / sizeof(myArray[0]) << std::endl;
    
        13
  •  3
  •   zangw    10 年前

    以下是 ArraySize Google Protobuf .

    #define GOOGLE_ARRAYSIZE(a) \
      ((sizeof(a) / sizeof(*(a))) / static_cast<size_t>(!(sizeof(a) % sizeof(*(a)))))
    
    // test codes...
    char* ptr[] = { "you", "are", "here" };
    int testarr[] = {1, 2, 3, 4};
    cout << GOOGLE_ARRAYSIZE(testarr) << endl;
    cout << GOOGLE_ARRAYSIZE(ptr) << endl;
    

    ARRAYSIZE(arr)通过检查 数组)和sizeof(*(arr))(一个数组中的字节数 元素)。如果前者可以被后者整除,那么arr可能是 实际上是一个数组,在这种情况下,除法结果是 我们生成一个编译器错误来防止代码 编译。

    !(sizeof(a)&sizeof(*(a)))到尺寸,以确保最终 结果具有类型大小。

    这个宏不完美,因为它错误地接受了 大小。因为我们所有的代码都要经过32位编译器, 如果指针是4字节,这意味着指向

        14
  •  3
  •   Przemek Marcinkiewicz    8 年前

    对于C++/CX(当在VisualStudio中使用C++编写UWP应用程序)时,我们可以通过简单地使用数组来找到数组中的值个数。 size()

    源代码:

    string myArray[] = { "Example1", "Example2", "Example3", "Example4" };
    int size_of_array=size(myArray);
    

    如果你 cout size_of_array 输出为:

    >>> 4
    
        15
  •  2
  •   David Gladson    9 年前
     length = sizeof(array_name)/sizeof(int);
    
        16
  •  1
  •   Menelaos Kotsollaris    10 年前

    一个使用泛型的好解决方案:

    template <typename T,unsigned S>
    inline unsigned arraysize(const T (&v)[S]) { return S; }
    

    然后直接打电话 arraysize(_Array); 获取数组的长度。

    Source

        17
  •  1
  •   Scy    9 年前

    template <class T, size_t N>
    char (&helper(T (&)[N]))[N];
    
    #define arraysize(array) (sizeof(helper(array)))
    
    int main() {
        int a[10];
        std::cout << arraysize(a) << std::endl;
        return 0;
    }
    
        18
  •  1
  •   Chen Li    8 年前

    我在这里提供了一个棘手的解决方案:

    你总是可以储存 length 在第一个元素中:

    // malloc/new
    
    arr[0] = length;
    arr++;
    
    // do anything. 
    int len = *(arr-1);
    
    free(--arr); 
    

    --arr 调用时 free

        19
  •  1
  •   Rezoanul Alam Riad    7 年前

    可以通过以下方法找到数组的长度:

    int  arr[] = {1, 2, 3, 4, 5, 6}; 
    int size = *(&arr + 1) - arr; 
    cout << "Number of elements in arr[] is "<< size; 
    return 0;
    
        20
  •  1
  •   Amado Saladino    7 年前

    您只需使用以下代码片段:

    #include <iostream>
    #include <string>
    #include <array>
    
    using namespace std;
    
    int main()
    {
    
      array<int,3> values;
      cout << "No. elements in valuea array: " << values.size() << " elements." << endl;
      cout << "sizeof(myints): " << sizeof(values) << endl;
    
    }
    

    http://www.cplusplus.com/reference/array/array/size/

        21
  •  0
  •   Das_Newb    12 年前

    只是一个想法,但只是决定创建一个计数器变量并将数组大小存储在位置[0]中。我删除了函数中的大部分代码,但在退出循环后,Prime(0)被分配为“A”的最终值。我试过使用向量,但VS Express 2013不太喜欢。还要注意,“a”从1开始以避免覆盖[0],它在开始时初始化以避免错误。我不是专家,只是想分享一下。

    int prime[] = {0};
    int primes(int x, int y){
        using namespace std; int a = 1;
        for (int i = x; i <= y; i++){prime[a] = i; a++; }
        prime[0] = a; return 0;
    }
    
        22
  •  0
  •   Johan Jönsson    9 年前

    避免将类型与sizeof一起使用,如 sizeof(array)/sizeof(char)

    在visual studio中,如果 sizeof(array)/sizeof(*array) . 你可以简单地打字 _countof(array)

        23
  •  0
  •   Raymond Iacobacci    8 年前

    unsigned int x[] -> int x[]
    

        24
  •  0
  •   bobbogo    7 年前

    最常见的原因之一是,您希望将数组传递给函数,而不必为其大小传递另一个参数。您通常也希望数组大小是动态的。该数组可能包含对象,而不是基元,并且对象可能很复杂,因此size_of()是计算计数的不安全选项。

    如果使用STL容器替代基元数组,则此SO post可能用于初始化它: What is the easiest way to initialize a std::vector with hardcoded elements?

    下面是一个我正在使用的方法,它可以在编译器和平台上普遍使用:

    class MyObject;
    
    struct MyObjectList
    {
        std::list<MyObject> objects;
        MyObjectList& operator<<( const MyObject o )
        { 
            objects.push_back( o );
            return *this; 
        }
    };
    

    您可以创建以结构为参数的函数,例如:

    someFunc( MyObjectList &objects );
    

    someFunc( MyObjectList() << MyObject(1) <<  MyObject(2) <<  MyObject(3) );
    

    这样,您就可以在一个干净的行中构建一个动态大小的对象集合并将其传递给一个函数!

        25
  •  0
  •   Bob Warner    6 年前

    回答:“int number_of_elements==sizeof(array)/sizeof(array[0])”

    说明:由于编译器为每种类型的数据设置了一个特定大小的内存块,而数组只是其中的一组,所以只需将数组大小除以数据类型的大小即可。如果我有一个30个字符串的数组,那么我的系统会为数组的每个元素(字符串)留出24个字节。30个元素,总共720个字节。720/24==30个元素。小而紧凑的算法是:

    “int number_of_elements==sizeof(array)/sizeof(array[0])”,等于;

    “元素数==720/24”

        26
  •  -4
  •   miksiii    12 年前

    假设在页面顶部声明了全局数组

    int global[] = { 1, 2, 3, 4 };
    

    要找出数组中有多少元素(在c++中),请键入以下代码:

    sizeof(global) / 4;