2014-03-27 30 views

回答

0
int max1 = std::max(x, y); 
int final_max = std::max(max1, z); 

std::max_element

// min_element/max_element example 
#include <iostream>  // std::cout 
#include <algorithm> // std::min_element, std::max_element 

bool myfn(int i, int j) { return i<j; } 

struct myclass { 
    bool operator() (int i,int j) { return i<j; } 
} myobj; 

int main() { 
    int myints[] = {3,7,2,5,6,4,9}; 

    // using default comparison: 
    std::cout << "The smallest element is " << *std::min_element(myints,myints+7) << '\n'; 
    std::cout << "The largest element is " << *std::max_element(myints,myints+7) << '\n'; 

    // using function myfn as comp: 
    std::cout << "The smallest element is " << *std::min_element(myints,myints+7,myfn) << '\n'; 
    std::cout << "The largest element is " << *std::max_element(myints,myints+7,myfn) << '\n'; 

    // using object myobj as comp: 
    std::cout << "The smallest element is " << *std::min_element(myints,myints+7,myobj) << '\n'; 
    std::cout << "The largest element is " << *std::max_element(myints,myints+7,myobj) << '\n'; 

    return 0; 
} 

http://www.cplusplus.com/reference/algorithm/max_element/

0

快速,constexpr(编译时间),和通用(live example):

template <typename F> 
struct fold 
{ 
    template <typename A> 
    constexpr typename std::decay <A>::type 
    operator()(A&& a) const { return std::forward <A>(a); } 

    template <typename A, typename... An> 
    constexpr typename std::common_type <A, An...>::type 
    operator()(A&& a, An&&... an) const 
     { return F()(std::forward <A>(a), operator()(std::forward <An>(an)...)); } 
}; 

struct max_fun 
{ 
    template <typename A, typename B> 
    constexpr typename std::common_type <A, B>::type 
    operator()(A&& a, B&& b) const 
     { return a > b ? std::forward <A>(a) : std::forward <B>(b); } 
}; 

using max = fold <max_fun>; 

int main() 
{ 
    cout << ::max()(5, 9, -2, 0.1) << endl; 
} 

这比涉及容器上的运行时迭代的任何解决方案更快,因为有没有指针递增,也没有取消引用。它相当于一个硬编码的三元运算符序列。

只要为它们定义了std::common_type,它就接受任意数量的任意类型的参数。

作为constexpr函数,它可以用于在编译时计算积分值并使用它,例如,作为模板参数。

只需将max_fun替换为另一个函数对象,便可轻松进行除max以外的任何折叠/缩小/累加操作。

相关问题