Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass a temporary array?

How can I pass a temporary array? I want to do something like this:

#include <iostream>

int sum(int arr[]) {
    int answer = 0;
    for (const auto& i : arr) {
        answer += i;
    }
    return answer;
}

int main() {
    std::cout << sum( {4, 2} ) << std::endl;       // error
    std::cout << sum( int[]{4, 2} ) << std::endl;  // error
}

Do I need a positive integer literal in the function parameter's braces []? If I include that literal, will it limit what arrays I can pass to only arrays of that size? Also, how can I pass array elements by rvalue reference or const reference? Because the above sample doesn't compile, I presume making the function's parameter type int&&[] or const int&[] won't work.

like image 605
CodeBricks Avatar asked Feb 19 '17 20:02

CodeBricks


People also ask

How do you create a temp array in C++?

You will need to create a temporary array to sort the values (to preserve the ordering of numbers). Do not sort the private member numbers array. Dynamically allocate/deallocate a temporary array in your getMedian function to determine the median.

Can you pass an array in C++?

C++ does not allow to pass an entire array as an argument to a function. However, You can pass a pointer to an array by specifying the array's name without an index.

How to Pass array elements to a function in C?

To pass an entire array to a function, only the name of the array is passed as an argument. result = calculateSum(num); However, notice the use of [] in the function definition. This informs the compiler that you are passing a one-dimensional array to the function.


1 Answers

First off, you cannot pass arrays as prvalues, so your function needs to take a reference. Second, the size of the array is part of the type, so your function probably needs to be part of a template. Third, writing array temporaries is lexically a bit silly, so you need some noise.

Putting it all together, the following ought to work

template <std::size_t N>
int sum(const int (&a)[N])
{
    int n = 0;
    for (int i : a) n += i;
    return n;
}

int main()
{
    std::cout << sum({1, 2, 3}) << "\n";
}

int main()
{
    using X = int[3];
    std::cout << sum(X{1, 2, 3}) << "\n";
}

The syntactic noise can be generalized slightly with an alias template:

template <std::size_t N> using X = int[N];

Usage: sum(X<4>{1, 2, 3, 4}) (You cannot have the template parameter deduced from the initializer.) Edit: Thanks to Jarod42 for pointing out that it is in fact perfectly possible to deduce the template argument from a braced list; no type alias is needed.

like image 126
Kerrek SB Avatar answered Sep 19 '22 21:09

Kerrek SB