티스토리 뷰

반응형

algorithm 헤더의 함수 중

두 값을 비교하여 최대, 최소값을 리턴해주는 max(), min() 함수가 있다. 

 

그런데 두 값이 아니라 배열이나 벡터에서 정해진 구간 중 최대/최소값을 알려주는 함수는 없을까?

결론적으로, 존재한다.

 

 

 max_element , min_element 함수란? 

이 함수 또한 algorithm 헤더에 있는데, 

구간 안에서(array, list, vector  등) 최대, 최소값을 구하는 함수인

max_element()min_element() 함수가 존재한다.

 

그런데 이 함수는 값 자체를 리턴하지 않고 그 값의 주소인 iterator(반복자)를 리턴한다.

C++에서는 배열 역시 array라는 클래스 형 객체로 취급됩니다.

그래서 주소값에 관해서 이터레이터 연산이 가능하게 되어 있습니다.

 

따라서 값을 참조하려면 * 연산자를 붙여야 합니다.

이 값을 저장하고 싶다면 배열의 경우 포인터, 벡터 등의 경우 해당 이터레이터 변수에 대입하시면 됩니다.

 

max_element()나 min_element()는 둘다 모든 요소에 접근을 해야 하기 때문에,

모든 STL 컨테이너에 대해서 선형으로 동작한다. 즉 시간 복잡도가 O(n)이다.

 

 


 사용 예시 

#include <iostream>
#include <algorithm>
#include <vector>
#include <list>
#include <string>

using namespace std;

int main() {
	int test_arr[] = { 2, 4, 3, 6, 1, 7 };
	vector<int> test_vec = { 2, 4, 3, 6, 1, 7 };
	list<int> test_list = { 2, 4, 3, 6, 1, 7 };
	string test_string = "algorithm";

	//array
	cout << "min array: " << *min_element(test_arr, test_arr + 6) << endl;
	cout << "max array: " << *max_element(test_arr, test_arr + 6) << endl;

	//vector
	cout << "min vector: " << *min_element(test_vec.begin(), test_vec.end()) << endl;
	cout << "max vector: " << *max_element(test_vec.begin(), test_vec.end()) << endl;

	//list
	cout << "min list: " << *min_element(test_list.begin(), test_list.end()) << endl;
	cout << "max list: " << *max_element(test_list.begin(), test_list.end()) << endl;

	//string 
	cout << "min list: " << *min_element(test_string.begin(), test_string.end()) << endl;
	cout << "max list: " << *max_element(test_string.begin(), test_string.end()) << endl;

	return 0;
}

iterator를 리턴하기 때문에 값에 접근하려면 * 연산자를 통해 접근한다.

 

반응형
댓글
반응형
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday