user3478252
user3478252

Reputation: 17

Using array methods inside a function

How would you use array methods such as .size() and .empty() in a function if you can only pass pointers to the array, since pointers just point to the first element?

I'm specifically asking about using array methods and not about finding ways to check the array size or whether the array is empty.

For example, how would you get array.empty() in the code below to work?

class Solution{
public:
    void testArray(int &array)[5]){  //or (int* array) or (int array[])
        std::cout << array.empty() << std::endl;
    }
}

int main(int argc, const char * argv[])
{
    int a1[] = {1,2,3,4,5};
    Solution s1;
    s1.testArray(a1);
}

Upvotes: 0

Views: 62

Answers (1)

cdhowie
cdhowie

Reputation: 169008

You are confusing the type int[5] with std::array<int, 5>. These are different things.

The first type (a "bare" array) has no members and can decay into a pointer-to-int automatically, which does indeed point to the first element and conveys no information about the array's length.

std::array is a template class that provides bounds-checking (using std::array::at()) and other standard STL container methods on top of a bare array.

Replace int a1[] = {1,2,3,4,5}; with std::array<int, 5> a1 = {{1,2,3,4,5}}; (and update the signature of Solution::testArray() to take a std::array<int, 5> const & parameter) and you will be able to use these methods.

Upvotes: 1

Related Questions