A simple generic template function for getting the minimum and maximum from STL container and simple arrays.
Nothing too complicated, I just liked this example.
1: template<class Iterator>
2: pair<Iterator, Iterator> minMaxFinder(Iterator begin, Iterator end)
3: {
4: Iterator min = begin;
5: Iterator max = begin;
6: for(++begin ; begin != end; ++begin) {
7: if(*begin > *max) {
8: max = begin;
9: }
10: else if(*begin < *min) {
11: min = begin;
12: }
13: }
14: return pair<Iterator, Iterator>(min, max);
15: }
16: int main()
17: {
18: int iArr[] = {15, 5, 70, 2};
19: pair<int*, int*> minmax = minMaxFinder(&iArr[0], &iArr[4]);
20: cout << *minmax.first << ", " << *minmax.second << endl;
21: list<string> sList;
22: sList.insert(sList.end(), "small");
23: sList.insert(sList.end(), "smallish");
24: sList.insert(sList.end(), "big");
25: sList.insert(sList.end(), "biggish");
26: pair<list<string>::iterator, list<string>::iterator>
27: minmaxS = minMaxFinder(sList.begin(), sList.end());
28: cout << *minmaxS.first << ", " << *maxminS.second << endl;
29: return 0;
30: }
Code formatted with http://codeformatter.blogspot.com
No comments:
Post a Comment