Element count of an array in C++

前端 未结 11 1607
[愿得一人]
[愿得一人] 2020-12-05 10:38

Let\'s say I have an array arr. When would the following not give the number of elements of the array: sizeof(arr) / sizeof(arr[0])?

I can

相关标签:
11条回答
  • 2020-12-05 10:40

    First off, you can circumvent that problem by using std::vector instead of an array. Second, if you put objects of a derived class into an array of a super class, you will experience slicing, but the good news is, your formula will work. Polymorphic collections in C++ are achieved using pointers. There are three major options here:

    • normal pointers
    • a collection of boost::shared_ptr
    • a Boost.Pointer Container
    0 讨论(0)
  • 2020-12-05 10:40

    It seems that if you know the type of elements in the array you can also use that to your advantage with sizeof.

    int numList[] = { 0, 1, 2, 3, 4 };
    
    cout << sizeof(numList) / sizeof(int);
    
    // => 5
    
    0 讨论(0)
  • 2020-12-05 10:42

    Since C++17 you can also use the standardized free function: std::size(container) which will return the amount of elements in that container.

    example:

    std::vector<int> vec = { 1, 2, 3, 4, 8 };
    std::cout << std::size(vec) << "\n\n";    // 5
    
    int A[] = {40,10,20};
    std::cout << std::size(A) << '\n';      // 3
    
    0 讨论(0)
  • 2020-12-05 10:43

    I know is old topic but what about simple solution like while loop?

    int function count(array[]) {
    
        int i = 0;
    
        while(array[i] != NULL) {
    
            i++;
    
        }
    
        return i;
    
    }
    

    I know that is slower than sizeof() but this is another example of array count.

    0 讨论(0)
  • 2020-12-05 10:44

    No that would still produce the right value because you must define the array to be either all elements of a single type or pointers to a type. In either case the array size is known at compile time so sizeof(arr) / sizeof(arr[0]) always returns the element count.

    Here is an example of how to use this correctly:

    int nonDynamicArray[ 4 ];
    
    #define nonDynamicArrayElementCount ( sizeof(nonDynamicArray) / sizeof(nonDynamicArray[ 0 ]) )
    

    I'll go one further here to show when to use this properly. You won't use it very often. It is primarily useful when you want to define an array specifically so you can add elements to it without changing a lot of code later. It is a construct that is primarily useful for maintenance. The canonical example (when I think about it anyway ;-) is building a table of commands for some program that you intend to add more commands to later. In this example to maintain/improve your program all you need to do is add another command to the array and then add the command handler:

    char        *commands[] = {  // <--- note intentional lack of explicit array size
        "open",
        "close",
        "abort",
        "crash"
    };
    
    #define kCommandsCount  ( sizeof(commands) / sizeof(commands[ 0 ]) )
    
    void processCommand( char *command ) {
        int i;
    
        for ( i = 0; i < kCommandsCount; ++i ) {
            // if command == commands[ i ] do something (be sure to compare full string)
        }
    }
    
    0 讨论(0)
  • 2020-12-05 10:44

    Use the Microsoft "_countof(array)" Macro. This link to the Microsoft Developer Network explains it and offers an example that demonstrates the difference between "sizeof(array)" and the "_countof(array)" macro.

    Microsoft and the "_countof(array)" Macro

    0 讨论(0)
提交回复
热议问题