templates & iterators & pointers...

So, I've been playing with this toy example for finding the max in a container, trying to get it into a more generalized form.

Now, I've lost my overloading (between max of two items and max in a container) and I have this nasty pointer everywhere (because I can't figure out how to return the max from mmaxc).

I was also trying to make a wrapper for arrays like the one for vector, but the sizeof trick doesn't work in the new scope (its a pointer).

Yes, I know, max is in STL algorithms, that's not the point.

Anyway, any suggestions would be helpful.
Thanks.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
#include <iostream>
#include <vector>
#include <string>

using namespace std;

template <class T>
inline T mmax(const T &a, const T &b){ return (a>b) ? a : b; }

template <class T>
inline T mmax(vector<T> &v){ return *mmaxc(v.begin(),v.end()); }

template <class itType>
itType mmaxc(itType first, itType last);

int main()
{
    int a=5,b=6, iarr[]={5,4,9,65,21,1000,44,6};
    double c=12.4,d=5.32, darr[]={5.22,1000.1,53.21,12.5};
    string s="sadf",t="jwewet", sarr[]= "asfgh","sg43g","Asg","hdsadh","zdsadhshdash"};
    
    vector<int> ivec(iarr, iarr+8);
    vector<double> dvec(darr, darr+4);
    vector<string> svec(sarr, sarr+5);
    
    cout << "int:  " << mmax(a,b) << endl
         << "dbl:  " << mmax(c,d) << endl
         << "str:  " << mmax(s,t) << endl
         
         << "aint: " << *mmaxc(iarr,iarr+8) << endl
         << "adbl: " << *mmaxc(darr,darr+4) << endl
         << "astr: " << *mmaxc(sarr,sarr+5) << endl
         
         << "vint: " << mmax(ivec) << endl
         << "vdbl: " << mmax(dvec) << endl
         << "vstr: " << mmax(svec) << endl
     ;
    
    return 0;
}

template <class itType>
itType mmaxc(itType first, itType last)
{
    itType m=first;
    while(++first!=last){ *m=mmax(*m,*first); }
    return m;
}
I figured out the overloading for arrays:

1
2
3
4
5
6
7
8
9
10
template <class T, int m>
inline T mmax(T (&arr)[m]){ return *mmaxc(arr,arr+m); }
//...
int main()
{
    //...
    << "aint: " << mmax(iarr) << endl;
    //...
}


Which almost fixes the pointer problem or at least hides it from the user...somwhat...
Well, STL already provides everything you've done above.

std::max( a, b )
std::min( a, b )

std::max_element( first, last )
std::min_element( first, last )

in

<algorithm>
I know, I'm just doing this for my on personal pleasure.

Yes, I know, max is in STL algorithms, that's not the point.

Topic archived. No new replies allowed.