Program Club

벡터에 std :: max_element 사용

proclub 2020. 10. 25. 13:21
반응형

벡터에 std :: max_element 사용


두 배의 벡터에서 최소 및 최대 요소 를 사용 std::min_element하고 std::max_element반환 하려고합니다 . 내 컴파일러는 내가 현재 사용하려는 방식을 좋아하지 않으며 오류 메시지를 이해하지 못합니다. 물론 최소 / 최대를 찾기위한 절차를 직접 작성할 수 있지만 함수를 사용하는 방법을 이해하고 싶습니다.

#include <vector>
#include <algorithm>

using namespace std;

int main(int argc, char** argv) {

    double cLower, cUpper;
    vector<double> C;

    // code to insert values in C not shown here

    cLower = min_element(C.begin(), C.end());
    cUpper = max_element(C.begin(), C.end());

    return 0;
}

다음은 컴파일러 오류입니다.

../MIXD.cpp:84: error: cannot convert '__gnu_cxx::__normal_iterator<double*, std::vector<double, std::allocator<double> > >' to 'double' in assignment
../MIXD.cpp:85: error: cannot convert '__gnu_cxx::__normal_iterator<double*, std::vector<double, std::allocator<double> > >' to 'double' in assignment

누군가 내가 뭘 잘못하고 있는지 설명해 주시겠습니까?


min_elementmax_element반환 반복자, 값 없습니다. 그래서 당신은 *min_element...*max_element....


다른 사람이 말했다,로 std::max_element()std::min_element()반환 반복자 해야 할 역 참조 얻기 위해 값을 .

(단지 값이 아닌) 반복기를 반환하는 이점은 최대 (또는 최소) 값을 사용하여 컨테이너에서 (첫 번째) 요소 위치 를 결정할 수 있다는 것 입니다.

예를 들어 (간결성을 위해 C ++ 11 사용) :

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

int main()
{
    std::vector<double> v {1.0, 2.0, 3.0, 4.0, 5.0, 1.0, 2.0, 3.0, 4.0, 5.0};

    auto biggest = std::max_element(std::begin(v), std::end(v));
    std::cout << "Max element is " << *biggest
        << " at position " << std::distance(std::begin(v), biggest) << std::endl;

    auto smallest = std::min_element(std::begin(v), std::end(v));
    std::cout << "min element is " << *smallest
        << " at position " << std::distance(std::begin(v), smallest) << std::endl;
}

결과 :

Max element is 5 at position 4
min element is 1 at position 0

노트 :

std::minmax_element()위의 주석에서 제안한대로 사용하면 큰 데이터 세트의 경우 더 빠를 수 있지만 약간 다른 결과를 얻을 수 있습니다. 내 예를 들어 위의 동일 합니다만, "최대"요소의 위치는 것 9때문에 ...

여러 요소가 가장 큰 요소에 해당하는 경우 마지막 요소에 대한 반복기가 반환됩니다.


min/max_element return the iterator to the min/max element, not the value of the min/max element. You have to dereference the iterator in order to get the value out and assign it to a double. That is:

cLower = *min_element(C.begin(), C.end());

참고URL : https://stackoverflow.com/questions/10158756/using-stdmax-element-on-a-vectordouble

반응형