IronCode
IronCode

Reputation: 27

Template Class Array

I am trying to do a project for an algorithms class that requires implementing different sorting algorithms. I am trying to declare an array using the template class as shown. I have to keep the function definitions the same and therefore cannot change any of the parameters. My question is for my array declaration, I get the error "Non type template argument is a non constant expression." What is the correct way to declare a template array? Any help will be appreciated.

#ifndef __SORTING_HPP
#define __SORTING_HPP

#include "SortingHelper.h"
#include <iostream>
template <class T> 
class Sorting
{    
    public:
        T selectionsort(T* data, int size);
        T insertionsort(T* data, int size);
        T mergesort(T* data, int size, T* temp);
        T quicksort(T* data, int size);
        T data;
};
template <class T>  void selectionsort(T* data, int size)
{
    std::array<T*, size> myarray = data;
    int min = 0;
    int temp = 0;
    if (isSorted(data, size))
    {
        return *data;
    }
    else
    {
        for (int i=0; i < size - 1; i++)
        {
            min = i;
            for (int j=i+1; j < size; j++)
            {
                if (data[j] < data[min])
                min= j;
           }
           if (min != i)
           {
                temp = data[i];
                data[i] = data[min];
                data[min] = temp;
           }
        }
   }
}
#endif

Upvotes: 0

Views: 242

Answers (1)

Christian Hackl
Christian Hackl

Reputation: 27548

template <class T>  void selectionsort(T* data, int size)
{
    std::array<T*, size> myarray = data;

size is only known at run time. The size of an std::array has to be known at compile time.

There are two ways to fix this:

  1. Use std::vector<T*> instead of std::array<T*, size>.

  2. Make size a template argument: template <class T, int size> void selectionsort(T* data).

What's better depends on what you actually want to do.


Mind that I'm not sure that your code really does what you intend it to do. You seem to be using T* in your functions' parameters as a way to say "pointer to a number of Ts", while in your selectionsort function you are suddenly dealing with a collection of T pointers.

In other words, std::array<T*, size> (or std::vector<T*>) is a collection of T*, not a collection of T. You will probably want to use std::array<T, size> (or std::vector<T>) and then use the T* that you receive in the function to copy the T objects that the T* points to into the container. For example:

std::vector<T> myarray(data, data + size);

Upvotes: 2

Related Questions