[C/C++] max_element() / min_element()

Onam Kwon·2022년 11월 28일
0

C/C++

목록 보기
3/12

max & min

  • C++ 알고리즘 max_element() min_element()는 범위 내에있는 최댓값이나 최솟값의 위치를 가리키는 iterator(이터레이터)를 반환한다.
    • 만약 여러개의 요소들이 조건을 만족한다면 첫번째로 만족하는 요소를 반환한다.
  • <algorithm>라이브러리에서 이 기능을 제공하므로 사용하려면 포함해줘야한다.
  • max_element() min_element() 둘다 모든 요소에 접근하면서 비교하기 때문에 시간복잡도는 당연히 O(N)

GitHub source code

max_element

  • 가장 큰 값을 반환하며 만약 여러개의 요소들이 조건을 만족한다면 첫번째로 만족하는 요소를 반환한다.
    • 값을 반환하는게 아닌 값의 위치를 가리키는 이터레이터를 반환한다.

min_element

  • 가장 작은 값을 반환하며 만약 여러개의 요소들이 조건을 만족한다면 첫번째로 만족하는 요소를 반환한다.
    • 값을 반환하는게 아닌 값의 위치를 가리키는 이터레이터를 반환한다.

전체코드

#include <iostream>
#include <algorithm>
#include <vector>

using namespace std;

int main() {

    vector<int> v = {1,3,5,8,2,6};
    cout<<"v: ";
    for(const auto &item: v) cout<<item<<" "; cout<<endl;

    // max_element()
    // Returning max element's iterator.
    // You have to use pointer to access the object. => *t
    auto t = max_element(v.begin(), v.end());
    cout<<"*t: "<<*t<<endl;

    // To get the index of the value, get the distance from the beginning to itself.
    int index = distance(v.begin(), t);
    cout<<"index of the maximum value: "<<index<<endl;


    // min_element()
    // Returning min element's iterator.
    // You have to use pointer to access the object. => *t
    auto c = min_element(v.begin(), v.end());
    cout<<"*c: "<<*c<<endl;

    // To get the index of the value, get the distance from the beginning to itself.
    int indexC = distance(v.begin(), c);
    cout<<"index of the minimum value: "<<indexC<<endl;

    return 0;
}
~/De/D/C/P/Algorithms/A/MaxElement main ❯ ./main.out                   22:32:53
v: 1 3 5 8 2 6
*t: 8
index of the maximum value: 3
*c: 1
index of the minimum value: 0

References

profile
권오남 / Onam Kwon

0개의 댓글