【问题标题】:please help me with max_element function in c++ stl请帮助我使用 c++ stl 中的 max_element 函数
【发布时间】:2021-05-19 11:34:42
【问题描述】:

下面是我的代码,我是 C++ 新手,请帮忙解释一下为什么会出错,我想在元素中找到最大值 而不使用任何额外的空间

代码:

#include <bits/stdc++.h>
using namespace std;
    
int main() {
    cout<<*max_element({4,6,2,5});
}

错误:

    error : prog.cpp: In function ‘int main()’:
    prog.cpp:5:30: error: no matching function for call to ‘max_element(<brace-enclosed initializer list>)’
      cout<<*max_element({4,6,2,5});
                                  ^
    In file included from /usr/include/c++/5/algorithm:62:0,
                     from /usr/include/x86_64-linux-gnu/c++/5/bits/stdc++.h:64,
                     from prog.cpp:1:
    /usr/include/c++/5/bits/stl_algo.h:5505:5: note: candidate: template<class _FIter> constexpr _FIter std::max_element(_FIter, _FIter)
         max_element(_ForwardIterator __first, _ForwardIterator __last)
         ^
    /usr/include/c++/5/bits/stl_algo.h:5505:5: note:   template argument deduction/substitution failed:
    prog.cpp:5:30: note:   candidate expects 2 arguments, 1 provided
      cout<<*max_element({4,6,2,5});
                                  ^
    In file included from /usr/include/c++/5/algorithm:62:0,
                     from /usr/include/x86_64-linux-gnu/c++/5/bits/stdc++.h:64,
                     from prog.cpp:1:
    /usr/include/c++/5/bits/stl_algo.h:5529:5: note: candidate: template<class _FIter, class _Compare> constexpr _FIter std::max_element(_FIter, _FIter, _Compare)
         max_element(_ForwardIterator __first, _ForwardIterator __last,
         ^
    /usr/include/c++/5/bits/stl_algo.h:5529:5: note:   template argument deduction/substitution failed:
    prog.cpp:5:30: note:   candidate expects 3 arguments, 1 provided
      cout<<*max_element({4,6,2,5});
                                 ^

【问题讨论】:

标签: c++ data-structures stl c++14


【解决方案1】:

您可以使用 max 代替 *max_element。参考如下:

cout<<max({4,6,2,5});

它会给出你想要的输出。

【讨论】:

    【解决方案2】:

    std::max_element 使用迭代器遍历列表以找到最大元素(参考:cppreference)。因此,一种方法是首先将值分配给向量,然后将其开始和结束迭代器传递给函数。

    #include <vector>
    ...
    
    int main() {
        std::vector<int> nums = {4,6,2,5};
        cout << *max_element(nums.begin(), nums.end());
    }
    

    您可以选择使用std::max 来获取最大元素。它有一个重载来接收初始化列表,并让您能够按原样完成它(参考:cppreference)。

    int main() {
        cout << max({4,6,2,5});
    }
    

    注意:尽量不要使用#include &lt;bits/stdc++.h,如该线程中所述:Why should I not #include <bits/stdc++.h>?

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-07-29
      • 2014-05-09
      • 1970-01-01
      • 2023-04-08
      • 2023-01-07
      • 1970-01-01
      • 1970-01-01
      • 2018-07-17
      相关资源
      最近更新 更多