Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to write a template function that takes an array and an int specifying array size

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?

like image 285
willfo Avatar asked Oct 20 '15 11:10

willfo


People also ask

How do I let the user choose the size of an array?

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.

How can you pass an array to a function?

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.

How do you declare a template 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.

How do you create an array of N size?

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.


1 Answers

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
like image 104
sehe Avatar answered Nov 02 '22 23:11

sehe