Help with templates

Hi. I'm trying to run a very simple program, using templates, which can do 2 things: sort an array, or reverse its elements. When I execute it, I get part of the answer, but also some weird numbers and/or letters. Any help much appreciated! (Oh, I'm using Microsoft Visual studio C++ 6)

[blue] This is my .h file: [/blue]

#ifndef TEMPLATE_H
#define TEMPLATE_H

void Sort(ANYTYPE x[]);
void Reverse(ANYTYPE x[]);


[blue] This is my source.cpp file [/blue]
void TEMPLATE::Sort(ANYTYPE x[])
ANYTYPE i, j, imax;
ANYTYPE tempsortarray;

for(j = 4; j >= 2; j--)
imax = 0;
for(i = 0; i < j; i++)
if(x[i] > x[imax])
{imax = i;}

tempsortarray = x[imax];
x[imax] = x[j-1];
x[j-1] = tempsortarray;
cout << x[i] << " ";

template <class ANYTYPE>
void TEMPLATE::Reverse(ANYTYPE x[])
ANYTYPE tempsortarray;
for(ANYTYPE i = 0; i < 4/2; i++)
tempsortarray = x[i];
x[i] = x[4 - i - 1];
x[4 - i - 1] = tempsortarray;
cout << x[i] << " ";

[blue] This is my main.cpp file [/blue]

#include <iostream.h>
#include "Template.h"
#include "Templatesource.cpp"

int main()
TEMPLATE y_char;
TEMPLATE z_float;
int a[4]={8, 6, 4, 2};
int b[4]={1, 3, 5, 7};
char c[4]={'a', 'b', 'c', 'd'};
char d[4]={'l', 'm', 'n', 'o'};
float e[4]={1.5, 2.5, 3.5, 4.5};
float f[4]={6.9, 7.9, 8.9, 9.9};


return 0;


  • There are clearly some problems with your code.
    First: In the sort function [italic]i,j[/italic] and [italic]imax[/italic], and [italic]i[/italic] in the reverse function should be of some integer type, say [blue]int[/blue]. You could of course argue that they always are in your example, which happens to be true, but its (very) bad coding style.

    Second: You try to print your arrays during your sorting and reversing. This doesnt work because your [italic]i[/italic] variable has wrong values. In the sorting you print from index 4 to index 1, where index 4 is clearly out of range, and in the reverse function you only print your two first array members. Try to keep things apart from one another. When you sort, sort but don't print; when you reverse your array, do that, but keep the printing for later. This will solve your problems in this example.

    Last but not least both your functions assume that the arrays they are working on has exactly 4 members. Dont assume too much in your functions or they will be quite useless.

    Microsoft Visual C++ has very powerful debugging tools, if you learn to use them they will be of great help.

Sign In or Register to comment.

Howdy, Stranger!

It looks like you're new here. If you want to get involved, click one of these buttons!


In this Discussion