Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Implement the following template functions in a header file called sorts.h. This

ID: 3824838 • Letter: I

Question

Implement the following template functions in a header file called sorts.h. This header file should have header guards (as usual) and should contain both the prototypes and definitions for the functions.

template <class T>
void buildList(vector<T>& set, const char* fileName)

This function should read items from an input file and put them into a vector. The first argument to this function is a reference to a vector object that will be used to store the items. The second argument is a C-style string containing the full pathname of the input file.

The function should first open the file for input, then read items from the file using the >> operator one at a time until end of file, inserting them into the vector. Finally, it should close the input file. Here's some pseudocode for the logic:

template <class T>
void printList(const vector<T>& set, int itemWidth, int numPerLine)

This function should print a list of items stored in a vector. The first argument to this function is a reference to a constant vector object that will contain the items to print. The second argument is an integer specifying the width an individual item should occupy when printed. The third argument is an integer specifying the maximum number of items that should be printed in a single line of output.

Explanation / Answer

Hi, Please find my implementation of both methods.

Please let me know in case of any issue.

template <class T>
void buildList(vector<T>& set, const char* fileName){

   T item;
   ifstream inFile(fileName);

   if(inFile.fail()){
       cout<<"Error in opening file"<<endl;
       return;
   }

   // reading file
   inFile>>item
   while(!inFile.eof()){
       set.push_back(item);
       inFile>>item;
   }

   inFile.close();
}


template <class T>
void printList(const vector<T>& set, int itemWidth, int numPerLine){
  
   int count = 0;

   for(int i=0; i<set.size(); i++){

       cout<<setw(itemWidth)<<set[i];

       count++;

       if(count == numPerLine){
           cout<<endl;
           count = 0;
       }
   }
}