Program Requirements:
Let A be an array of n elements. Write a template function that takes an unsorted array of type <class T> as an input parameter and feeds back a sorted array via the input parameter. Assume the operators < and > are defined for the class T. In this question, you may hardcode n=5. You must write all functions you call, and also needs to write a main() to test the following data arrays stored in a data file (data.txt):
1 9 3 4 6
4 1 9 3 6
1.1 4.1 3.1 5.2 6.3
t d b e f
I have got my program to run but the output only shows me this:
The initial list is 1 9 3 4 6
The sorted list is
Can anyone help me fix this problem. I think that my SortedList function is correctly set up but I am not sure why it is not giving me the correct output. I was hoping you guys could locate any of my errors or give me any advice. This is my first time learning templates so any help would be appreciated. Thanks
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
#define MAX_ELEMENTS 5
template < class T > void SortedList(T data[MAX_ELEMENTS])
{
// Sort the list
for (int count1 = 0; count1 < MAX_ELEMENTS; count1++) {
for (int count2 = 0; count2 < MAX_ELEMENTS; count2++) {
if (data[count2] > data[count2 + 1]) {
T temp = data[count2 + 1];
data[count2 + 1] = data[count2];
data[count2] = temp;
}
}
}
}
int main()
{
string data[5];
string temp;
ifstream infile;
infile.open("data.txt");
if (!infile)
cout << "Your file was not opened correctly";
else
while (!infile.eof()) {
for (int i = 0; i < MAX_ELEMENTS && !infile.eof(); i++) {
infile >> data[i];
}
cout << "The initial list is ";
for (int i = 0; i < MAX_ELEMENTS; i++) {
cout << data[i] << " ";
}
cout << endl;
cout << "Sorted list is " << endl;
SortedList(data);
infile.close();
system("pause");
return 0;
}
}