Jump to content

Question over a function template that returns range of vector

- - - - -

  • Please log in to reply
4 replies to this topic

#1
camouser1s

camouser1s

    Newbie

  • Members
  • Pip
  • 6 posts
This is the question from the assignment itself:
-Write a function template that returns the range of values stored in a vector, that is, the difference between the largest value and the smallest value, when operator < is assumed to be defined for type T.

This is what I have:

template <typename T>

int Range(vector<T> vec)

{

   for(int i = 0; i < (vec.size() - 1); i++)

     {

        while (vec[i] < vec[i + 1])

          {

             return (vec.begin() - vec.end());

           }

      }

}



How does this look? Feedback and criticism is appreciated. Thanks :)

#2
WingedPanther

WingedPanther

    A spammer's worst nightmare

  • Moderators
  • 16,831 posts
  • Location:Upstate, South Carolina
  • Programming Language:C, C++, PL/SQL, Delphi/Object Pascal, Pascal, Transact-SQL, Others
  • Learning:Java, C#, PHP, JavaScript, Lisp, Fortran, Haskell, Others
You haven't found the largest or smallest values, just the consecutive differences.
Programming is a branch of mathematics.
My CodeCall Blog | My Personal Blog

#3
Flying Dutchman

Flying Dutchman

    Programming God

  • Members
  • PipPipPipPipPipPipPip
  • 889 posts
  • Location:::1
You are actually returning negative vector's size. Your return statement is equivalent to this:

return 0 - vec.size();


A conclusion is where you got tired of thinking.
#define class struct    // All is public.

#4
camouser1s

camouser1s

    Newbie

  • Members
  • Pip
  • 6 posts
could i just do the min and max values with iterators ?

#5
WingedPanther

WingedPanther

    A spammer's worst nightmare

  • Moderators
  • 16,831 posts
  • Location:Upstate, South Carolina
  • Programming Language:C, C++, PL/SQL, Delphi/Object Pascal, Pascal, Transact-SQL, Others
  • Learning:Java, C#, PHP, JavaScript, Lisp, Fortran, Haskell, Others
You need to have a couple extra variables to keep track of the values pointed to by the iterators.
Programming is a branch of mathematics.
My CodeCall Blog | My Personal Blog




1 user(s) are reading this topic

0 members, 1 guests, 0 anonymous users