Thread: using Template Functions

  1. #1
    Registered User
    Join Date
    Sep 2006
    Location
    Martin, Tn
    Posts
    12

    using Template Functions

    To begin this is my first time using these forums. I am a C++ Newbie, I am in college taking a C++ Course and I am having trouble. My teacher knows the subject, but I feel he has a hard time getting it across to us the class. So I am asking for help clarifying some of the things he is trying to convey to us. Also I work all the time and have no time to visit him in his office to ask for further explanation. YES the following code is from my homework, NO I do not expect you to do my homework for me. But help is needed despreatly.

    This is the code that he gave to us, he asked us to make the fucntions into templates which I have done and tested by switching from an array of "ints" to an array of "chars" it still reads, sorts and prints so what I have changed on this version so far works, I have two other versions for the rest of the assignment that no longer work. here is the code as it stands, I will put the directions for completing the assignment after the code allong with what I would like as far as help goes...Again I DO NOT Expect you to do my homework I am simply trying to learn... SRY for the length.

    Code:
    #include <iostream>
    #include <cstring>
    using namespace std;
    
    template <class t> void printlist(ostream &os, t list[], int count);
    // prints list one item per line. user must
    // make sure that argument os has been opened in case
    // argument is a file stream and count is number of items 
    // stored in arguemtn list
    
    template <class t> void printlist(ostream &os, t list[], int count)
    {
     t i;
     for(i=0; i<count; i++)
        os << list[i] << endl;
     return ;
    }  // End Printlist
    
    template <class t> void readlist(istream &is, t list[], int &count, int max_to_read);
    // list is an array of integers, max_to_read is maximum number of
    // items that can be stored in list. on return count is set to
    // actual number of items read from is into argument list.
    // user must make sure that is has been opened in case of an input
    // file stream. Reads until max_to_read items have been stored in
    // array or end of file whichever comes first.
    
    template <class t> void readlist(istream &is, t list[], int &count, int max_to_read)
    {
     t temp;
     is >> temp;
     count = 0;
     while(count < max_to_read && !is.eof())
       {
        list[count++] = temp;
        is >> temp;
       }
     return;
    }  // End Readlist
    
    
    template <class t> void sortlist(t list[], int count);
    // sorts list into ascending order. count is number of items stored in 
    //array uses selection sort algorithm
    
    template <class t> void sortlist(t list[], int count)
    {
      t minpos;
      t i;
      int pass;
      count--;
      // make count-1 passes through list
      // note that count is decremented by 1 to save an operation
      // of subtracting one in the for header, which normally reads
      // pass< count -1. In the code to complete a pass through the 
      // list then to go to the end of the array, i must index 
      // from pass + 1 to count, which since decremented is the 
      // last position in the list where data are stored
      for(pass=0; pass<count; pass++) 
           {
            minpos = pass;
            for(i=pass+1; i<=count; i++)  // note above
                if (list[i] < list[minpos])
                    minpos = i;
            if(minpos != pass)            // save a swap maybe?
              swap(list[minpos], list[pass]);
           }
       return ;
    }  // End Sortlist
    
    int main(void)
     { 
      const int array_size = 20;  
      char list[array_size];
      int count;
      
      cout << "Enter integers (max 20) using ^D to terminate" << endl;
      readlist(cin, list, count, array_size);
      cout << "Done reading, sorting..." << endl << endl;
      sortlist(list, count);
      cout << "Sorted list" << endl;
      printlist(cout, list, count);
      cout <<"Done printing list. Total of " << count << " items."<< endl;
      system ("pause");
      return 0;
    } // End Main
    The directions for me to complete the homework,

    1.) make the three functions included here generic. (Which I have done and tested so that part works)

    2.) Then in the same program declare two arrays. One an array of floats and the other an array of (single) characters. Read the array of floats, sort and print. Then in the same program read the array of chars, sort and print. Note that since the input function reads until eof or the array is full, you will probably have to call cin.reset() between reads to reset the end of file flag.


    I see that the prog passes the array called "list" to the functions. I tried declaring two arrays one for "chars" and one for "floats" named "list" but of course I couldnt do that. so my question is, how do I declare 2 arrays of different types that I can pass through the functions. I have 2 other versions of this prog where I have modified the code so much that I am confused with them so I am dropping back and starting again.

    If you could either write an explanation in simple terms and or a small snippet of code to show an example of how this would be done so that I can take it and run with it to complete my homework. Please keep it simple, I am having a very hard time with this class and am in need of help. Again I appologize for the length of the post.

  2. #2
    vae victus! skorman00's Avatar
    Join Date
    Nov 2003
    Posts
    594
    you need two lists, so you need to declare two of them. You can pass each of them to the function seperately.
    Code:
    void foo( int a) 
    {
      cout << a;
    }
    ...
    int a = 1;
    int b = 2;
    foo( a );
    foo( b );

  3. #3
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,817
    Code:
    template <class t> void printlist(ostream &os, t list[], int count)
    {
     t i;
     for(i=0; i<count; i++)
        os << list[i] << endl;
     return ;
    }  // End Printlist
    That should be an int. What if you later try to printlist an array of structs? i becomes an instance of that struct which will be assigned to 0 and incremented throughout the loop?

    Likewise:
    Code:
    template <class t> void sortlist(t list[], int count)
    {
      t minpos;
      t i;
      int pass;
      count--;

    Quote Originally Posted by ashcan1979
    I see that the prog passes the array called "list" to the functions. I tried declaring two arrays one for "chars" and one for "floats" named "list" but of course I couldnt do that. so my question is, how do I declare 2 arrays of different types that I can pass through the functions. I have 2 other versions of this prog where I have modified the code so much that I am confused with them so I am dropping back and starting again.
    Internal to the functions, the arrays are operated upon as if they were named list. This is a seperate/distinct variable name from the variable name these arrays may be known as external to the functions. Just because a variable is named "list" in your main function does not mean that it is the same object refered to in the other functions even though the function argument's name is the same "list" variable. They are actually different objects. So, you need to create two arrays (named differently) and then pass them as arguments to the functions to sort/print them.

    Code:
    int intList[array_size];
    char charList[array_size];
    int intCount = 0;
    int charCount = 0;
    
    ...
    
    readlist(cin, intList, intCount, array_size);
    
    ...
    
    readlist(cin, charList, charCount, array_size);
    When you pass intList to the readlist function, the array will essentially be treated as if it were named list within readlist although it is called intList outside the readlist function. When it comes time to pass charList into the function, the same thing will happen, charList will be treated as if it were named list. The names of the variables in the function argument list have no bearing/restriction on the what the names of the variables actually passed into the function can be.
    Last edited by hk_mp5kpdw; 09-19-2006 at 02:19 PM.
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

  4. #4
    Registered User
    Join Date
    Sep 2006
    Location
    Martin, Tn
    Posts
    12
    Hey guys thanks for the help...I got home and redid the program and it works great...Also thanks HK for the brief description of how objects are passed throughout a program...Made a lot more sense than what my teacher rattled off to us..

    Well again thanks and I will probally be back asking more questions, I just hope that you all will be patient with me as I attempt to grasp C++.....

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Function template has already been defined
    By Elysia in forum C++ Programming
    Replies: 19
    Last Post: 04-14-2009, 10:17 AM
  2. Polynomials and ADT's
    By Emeighty in forum C++ Programming
    Replies: 20
    Last Post: 08-19-2008, 08:32 AM
  3. Specialising a member function with a template template parameter
    By the4thamigo_uk in forum C++ Programming
    Replies: 10
    Last Post: 10-12-2007, 04:37 AM
  4. Screwy Linker Error - VC2005
    By Tonto in forum C++ Programming
    Replies: 5
    Last Post: 06-19-2007, 02:39 PM
  5. Friend template functions
    By lyx in forum C++ Programming
    Replies: 4
    Last Post: 10-02-2003, 01:11 PM