simple min/max

I have a question about finding the maximum and minimum elements in a list. (The list in question will be quite small -- only 2 elements -- so I am hoping for an efficient solution to all of this.) Is there a way to do this simply and efficiently? I am making my switch over from Matlab and Mathematica to C++, so I was expecting to find a pre-defined function for this. I was surprised to learn that this function isn't part of math.h. Thanks!
by list do you mean std::list or an array? If you mean std::list you should not expect to find it in math.h (or cmath) because that is an old C header and C didn't have std::list. You can use std::max_element and std::min_element to get the max and min value of the list.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <list>
#include <algorithm>

int main()
{
	std::list<int> l;
	l.push_back(2);
	l.push_back(8);
	l.push_back(132);
	l.push_back(-2);
	l.push_back(53);
	l.push_back(24);
	
	std::list<int>::iterator max = std::max_element(l.begin(), l.end());
	std::list<int>::iterator min = std::min_element(l.begin(), l.end());
	
	std::cout << "Max: " << *max << std::endl;
	std::cout << "Min: " << *min << std::endl;
}


Last edited on
Sorry for the ambiguity. I meant an array.
The same code is valid for vectors:
1
2
3
4
        vector<int> l;
         // fill the vector
	std::vector<int>::iterator max = std::max_element(l.begin(), l.end());
	std::vector<int>::iterator min = std::min_element(l.begin(), l.end());


Read also this http://www.cplusplus.com/reference/algorithm/max_element/
Last edited on
pointers can work as iterators so max_element and min_element works for arrays too.
1
2
3
4
5
6
7
8
9
10
11
12
13
#include <iostream>
#include <algorithm>

int main()
{
	int arr[] = {2, 8, 132, -2, 53, 24};
	
	int* max = std::max_element(arr, arr + 6);
	int* min = std::min_element(arr, arr + 6);
	
	std::cout << "Max: " << *max << std::endl;
	std::cout << "Min: " << *min << std::endl;
}
Thank you for the responses. This definitely helps.
Topic archived. No new replies allowed.