如何使用C++中的STL找到数组的最小值和最大值
给定一个数组arr [],使用C++中的STL找到该数组的最小值和最大值。
例子:
输入: arr [] = {1,45,54,71,76,12}
输出: 最小值=1,最大值=76
输入: arr [] = {10,7,5,4,6,12}
输出: 最小值=4,最大值=12
方法:
- 使用提供的STL功能
*min_element(),可以找到Min或Minimum Element。 - 使用提供的STL功能
*max_element(),可以找到Max或Maximum Element。
语法:
*min_element (first, last);
*max_element (first, last);
若要使用*min_element()和*max_element(),必须将“algorithm”包括为头文件。
所使用的范围为[first,last],其中包含first和last之间的所有元素,但不包括last指向的元素。
以下是上述方法的实现:
//在C++中使用sort()和STL找到数组的最小值和最大值。
#include
using namespace std;
int main()
{
//获取数组
int arr[] = {1,45,54,71,76,12};
//计算大小
int n = sizeof(arr) / sizeof(arr[0]);
//打印数组
cout << "Array: ";
for (int i = 0; i < n; ++i)
cout << arr[i] << " ";
//查找最小元素
cout << "\nMin Element = " << *min_element(arr, arr + n);
//查找最大元素
cout << "\nMax Element = " << *max_element(arr, arr + n);
//将指针存储在地址中
int &min; = *min_element(arr, arr + n);
int &max; = *max_element(arr, arr + n);
cout<<"\nFinding the Element using address variable";
cout<<"\nMin Element = "<
输出
Array: 1 45 54 71 76 12
Min Element = 1
Max Element = 76
Finding the Element using address variable
Min Element = 1
Max Element = 76
时间复杂度:O(N)
辅助空间:O(1)
极客教程