I made program that ask user to enter number to create an array. Then the array get sorted and the mean, median, and mode gets calculated. My problem is I get errors for templates for finding the mean, median and mode. I think I am doing template wrong. Can anyone help me make a template for finding the mean, median, and mode?
I am pretty sure that for a method to be templated, the entire class would have to be templated as well (pretty sure means that I don't actually know for sure in this instance).
Either way, a template belongs in a header file - template classes and functions are instantiated at compile time, so you can't precompile a template and link it later on (you can precompile an instance of a template and link that later on though).
<int>Mode *mode= new Mode(a, size);
Would have to be
Mode<int> *mode= new Mode<int>(a,size);
Of course the class would have to be templated for that.
*Frustratingly shouts* I thought you solved this? An undefined reference means that you're invoking a function that hasn't got a body. Define the body for Mode::Mode( int *, int ).
template < typename Type >
class Class
{
public:
Class( );
private:
int Member;
public:
int Method( );
};
// Definitions:
template < typename Type >
Class< Type >::Class( ) : Member( 0 )
{ }
template < typename Type >
int Class< Type >::Method( )
{
return Member;
}
You can template a single method. It goes like this:
1 2 3 4 5 6 7 8 9 10 11 12
class Class
{
public:
template < typename Type >
Type Method( Type );
};
// Definition:
template < typename Type >
Type Class::Method( Type Param )
{
}
Don't place template definitions within source modules. Instead, declare the class along with its members. Then, define the body of each method underneath the class declaration, like I've done in my previous post.
He did create it correctly. It is pretty pointless to do it that way if the Mode isn't supposed to persist past the function it was created in, but there was no syntactic or semantic error there.
He knows the type at compile time.
There is no persistence.
There is no copy overhead (container). the class could be lightweight
There is no polymorphism.
So I think it is a mistake to use a pointer there. (remember that you need to delete it)
The same applies to the b and m "arrays". Moreover you could have a double deletion because you didn't define the copy constructor and the assignment operator. You should use a std::vector there. (or 'destructive' methods)