For a university exercise, I have been asked to write a template function "print();", which takes two arguments, 1: an array of a generic type, and 2: an int specifying the size of the array. The function should then print out every item in the array to the console. I am having some trouble with the function arguments. The code I currently have is:
template <typename Type>
Type print (Type a, Type b)
{
Type items;
Type array;
a = array;
b = items;
for (int i = 0; i < items; i++) {
std::cout << std::endl << "The element of the index " << i << " is " << array << std::endl;
std::cout << std::endl;
}
and in main():
print(Array[], 10);
Obviously putting Array as an argument isn't returning a value, so I am not sure what else to do. Any ideas?
You need to use a dynamically allocated array. int N; printf("Please enter size of array\n"); scanf("%d", &N); int *a = malloc(N * sizeof(int)); Then you can access it like a normal array.
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.
To instantiate a template function explicitly, follow the template keyword by a declaration (not definition) for the function, with the function identifier followed by the template arguments. template float twice<float>( float original ); Template arguments may be omitted when the compiler can infer them.
Given a number N, the task is to create an array arr[] of size N, where the value of the element at every index i is filled according to the following rules: arr[i] = ((i – 1) – k), where k is the index of arr[i – 1] that has appeared second most recently.
The correct way to write it is
Live On Coliru
#include <iostream>
template <typename T, size_t size> void print(const T (&array)[size])
{
for(size_t i = 0; i < size; ++i)
std::cout << array[i] << " ";
}
int main() {
int arr[] = { 1,2,3,4,99};
print(arr);
}
Prints
1 2 3 4 99
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