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.
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With