반응형
    
    
    
  반응형
    
    
    
  

* Cpp STL max_element, min_element의 사용법과
distance method를 사용해 벡터 내부의 최대/최소 원소의 인덱스를 구하는 방법에 대해 소개합니다.
#max_element / min element
usage
max_element(vector_name.begin(), vector_name.end())
min_element(vector_name.begin(), vector_name.end())
<algorithm> Header에 선언되어 있다.
벡터 내부의 최대/최소 원소의 첫 번째 위치를 "이터레이터" 형태로 반환한다.
반환타입이 "값"이 아닌 "이터레이터" 이기에 * 연산자를 사용해 값에 접근해야 한다.
#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;
int main() {
    
    vector<int> novs = {1, 2, 2, 5, 5, 3};
    
    auto max_it = max_element(novs.begin(), novs.end());
    auto min_it = min_element(novs.begin(), novs.end());
    
    cout << "max_element : " << *max_it << endl;
    cout << "min_element : " << *min_it << endl;
    
}max_element : 5
min_element : 1
#distance
usage
distance(first, last)
<iterator> 내부에 선언되어 있다.
두 이터레이터 사이의 거리를 계산하는 함수로 first 위치에서 last 위치까지 얼마나 떨어져 있는지 확인할 수 있다.
앞서 소개한 max/min_element를 last parameter에 탐색할 벡터의 시작점 (begin())을 first에 넣어주면 벡터 내부의 최대/최소 위치의 인덱스를 탐색할 수 있다.
#include <iostream>
#include <algorithm>
#include <vector>
#include <iterator>
using namespace std;
int main() {
    
    vector<int> novs = {1, 2, 2, 5, 5, 3};
    
    auto max_it = max_element(novs.begin(), novs.end());
    auto min_it = min_element(novs.begin(), novs.end());
    
    cout << "max_idx : " << distance(novs.begin(), max_it) << endl;
    cout << "min_idx : " << distance(novs.begin(), min_it) << endl;
    
}max_idx : 3
min_idx : 0
반응형
    
    
    
  'Algorithm > PS With C++' 카테고리의 다른 글
| Cpp Algorithm Technic Climits 가장 큰 최대, 최소값 설정하기 (0) | 2025.09.07 | 
|---|---|
| [Cpp] STL 2D Vector (0) | 2025.04.30 | 
| [C++] fill method (0) | 2025.01.26 | 
| Binary Search in C++ STL (1) | 2024.09.29 | 
| [C++] About STL Set Container in PS Algorithm (0) | 2024.09.17 |