Last active
April 13, 2019 01:47
-
-
Save 67hz/327256e7d7a0831ca7f4df420d81e108 to your computer and use it in GitHub Desktop.
passing array as ref to maintain size info in C++
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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