How do I find the length of an array?

前端 未结 27 2886
轮回少年
轮回少年 2020-11-21 23:10

Is there a way to find how many values an array has? Detecting whether or not I\'ve reached the end of an array would also work.

27条回答
  •  无人及你
    2020-11-21 23:30

    One of the most common reasons you would end up looking for this is because you want to pass an array to a function, and not have to pass another argument for its size. You would also generally like the array size to be dynamic. That array might contain objects, not primitives, and the objects maybe complex such that size_of() is a not safe option for calculating the count.

    As others have suggested, consider using an std::vector or list, etc in instead of a primitive array. On old compilers, however, you still wouldn't have the final solution you probably want by doing simply that though, because populating the container requires a bunch of ugly push_back() lines. If you're like me, want a single line solution with anonymous objects involved.

    If you go with STL container alternative to a primitive array, this SO post may be of use to you for ways to initialize it: What is the easiest way to initialize a std::vector with hardcoded elements?

    Here's a method that I'm using for this which will work universally across compilers and platforms:

    Create a struct or class as container for your collection of objects. Define an operator overload function for <<.

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

    You can create functions which take your struct as a parameter, e.g.:

    someFunc( MyObjectList &objects );
    

    Then, you can call that function, like this:

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

    That way, you can build and pass a dynamically sized collection of objects to a function in one single clean line!

提交回复
热议问题