/* Function template to compare strings */

Is there any way for this code to print : min( adr1, adr2 ) = hello /*?*/

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
#include <iostream>
/* Function template to compare strings */
template <class T> T minimum( T a, T b )
  {
   if( a < b ) return a; /* or return a < b ? a : b; */
          else return b;
  }

int main()
{
const char *adr1 = "world", *adr2 = "hello ";

std::cout << "min( adr1, adr2 ) = " << minimum( adr1, adr2 ) << "\n";

return 0;
}

/* This prints out : min( adr1, adr2 ) = world */

TIA
Last edited on
1
2
3
4
5
template < typename T > // generic minimum
const T& minimum( const T& a, const T& b ) { return b < a ? b : a ; }

const char* minimum( const char* a, const char* b ) // overload for C-style strings
{ return std::strcmp(a,b) > 0 ? b : a ; }
Thanks
I should have known that sending pointers to strings to my function would result in it comparing
the memory addresses of those strings. I hope I got that straight.
Topic archived. No new replies allowed.