Qt 快速求最值

1. 求最大值

const T &qMax(const T &a, const T &b)

2. 求最小值

const T &qMin(const T &a, const T &b)

3. 求三值的中间值

const T &qBound(const T &v1, 
                const T &v2, 
                const T &v3)

4. 求列表容器的最值

  • 利用C++标准库接口
1 #include<algorithm>
2 template<class ForwardIt, class Compare>
3 ForwardIt std::min_element(ForwardIt first, 
4                            ForwardIt last, 
5                            Compare comp)
6                            
7 ForwardIt std::max_element(ForwardIt first, 
8                            ForwardIt last, 
9                            Compare comp)
  • 示例
1 QStringList list{"1", "3", "2"};
2 QString maxValue = *std::max_element(list.begin(), list.end());
3 QString minValue = *std::min_element(list.begin(), list.end());
  • 特别地基于迭代器的容器都可以使用该方法。

5. 数组求最值

1 int array[] = {1, 5, 4, 3, 2, 0};
2 int maxValue = *std::max_element(array, 
3                                  array + sizeof(array)/sizeof(array[0]));
4                                  
5 int minValue = *std::min_element(array, 
6                                  array + sizeof(array)/sizeof(array[0]));
原文地址:https://www.cnblogs.com/ybqjymy/p/13322106.html