Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
passing array as ref to maintain size info in C++
// If std::array is not an option (e.g embedded), use the following tactic to maintain size info of array as param
// This method uses non-type template arguments to retain size of array.
// See std::begin() and std::end() for similar approaches.
#include <iostream>
using namespace std;
// @param h {T} represents highest number in given array
// used to determine size of hash array
template<typename T, size_t N>
void findDups(T (&a)[N], T h) // pass array of N refs (&a)
{
T *hashArr = new T[h]{0}; // zero-initialized on heap
for(int i = 0; i<N; i++)
hashArr[a[i]]++;
for(int j = 0; j <= h; j++)
if(hashArr[j] > 1)
cout << j << ":" << hashArr[j] << endl;
}
template<typename T, size_t N>
T ArraySum(T (&arr)[N])
{
T sum = 0;
for(auto el: arr)
sum += el;
return sum;
}
int main()
{
int arr[10] = {8,3,6,4,6,5,6,8,2,7};
// 8 represents highest number in arr
findDups(arr, 8);
// same principle to sum array
float f_arr[]{ 2.1212f,1.1f,3.23f,4.5f };
auto farray_sum = ArraySum(f_arr); // passing array is enough. no extra size_t param needed.
cout << "Float Array sum: " << farray_sum << endl;
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment