c++ Templates

This is a discussion on c++ Templates within the C++ Programming forums, part of the General Programming Boards category; template<typename T> int largest(T* myarray, int n) How would you write a program that uses the above template function to ...

  1. #1
    Registered User
    Join Date
    Mar 2005
    Posts
    18

    c++ Templates

    template<typename T> int largest(T* myarray, int n)

    How would you write a program that uses the above template function to find the largest element in an int array and in a float array???

  2. #2
    S Sang-drax's Avatar
    Join Date
    May 2002
    Location
    Göteborg, Sweden
    Posts
    2,072
    Code:
    int array[] = {2, 5, 1, 5, 7};
    int largestValue = largest(array, 5);
    Last edited by Sang-drax : Tomorrow at 02:21 AM. Reason: Time travelling

  3. #3
    Registered User
    Join Date
    May 2003
    Posts
    82
    Where is the problem?

    Can you implement it using a non-template function? If so, getting that code written and posted is a good first step.

  4. #4
    Registered User
    Join Date
    Mar 2005
    Posts
    18
    how would you implement the function to return the index of the largest element in an array with n elements?

  5. #5
    Kiss the monkey. CodeMonkey's Avatar
    Join Date
    Sep 2001
    Posts
    917
    Depends on the function code, dude.
    "If you tell the truth, you don't have to remember anything"
    -Mark Twain

  6. #6
    Registered User
    Join Date
    May 2003
    Posts
    82
    The logic is not too hard.

    The general concept is to start by assuming the first element is the largest.
    Then compare the current maximum value the next element. If the next element is larger, save its position instead. Go through the array, element by element in this manner. The final position in your max value variable should be the answer you're looking for.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Templates from DLL or static library problem
    By mikahell in forum C++ Programming
    Replies: 2
    Last Post: 01-01-2008, 01:49 AM
  2. Questions about Templates
    By Shamino in forum C++ Programming
    Replies: 4
    Last Post: 12-18-2005, 12:22 AM
  3. templates and inheritance problem
    By kuhnmi in forum C++ Programming
    Replies: 4
    Last Post: 06-14-2004, 03:46 AM
  4. When and when not to use templates
    By *ClownPimp* in forum C++ Programming
    Replies: 7
    Last Post: 07-20-2003, 10:36 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21