std max


1
2
3
4
5
6
7
8
#include <iostream>
int main () {
  std::cout << "max(1,2)==" << std::max(1,2) << '\n';
  std::cout << "max(2,1)==" << std::max(2,1) << '\n';
  std::cout << "max('a','z')==" << std::max('a','z') << '\n';
  std::cout << "max(3.14,2.73)==" << std::max(3.14,2.73) << '\n';
  return 0;
}

max(1,2)==2
max(2,1)==2
max('a','z')==z
max(3.14,2.73)==3.14

is there many code like this? i mean the max() if there is then why i have to mess with template?
Thats the point of the algorithms contained in <algorithm> - for common tasks (like max) you don't need to mess around with templates and write it yourself (even if it is just a one-liner). However, max isn't the only use of templates.

I presume you are asking this because you are currently learning how to use templates, and you have to write a maximum function? Look at it this way - its a learning exercise. The point is to learn the syntax of templates. I mean there are many other examples of exercises given which are already provided, such as a dynamic array (std::vector) or a sorting function (std::sort).

On a side note, if you are going to be using std::max you should really add #include <algorithm> to your code.
Last edited on
also did not even include <algorithm> so why is the code runnig?
it should be error in max()
Last edited on
Its likely that your compiler has <iostream> either including <algorithm> directly, or at some point defining max. The point is - its not portable, so moving to a different compiler (or a different version of the same compiler) might mean that it doesn't work. Get in the habit of including the files required for your functions.
Okay thank you. i get it.
can you give me a link that has the list of function template like the max()
A fairly easy one is the one on this site: http://www.cplusplus.com/reference/algorithm/ contains the most common functions. Sometime, if you have nothing to do, you can look through the various headers there and find all sorts of useful functions that you never knew existed!
can i use template function even i dont learn it just by using <algorithm>?
Last edited on
Topic archived. No new replies allowed.