头文件
#include<alorithm>
作用
用于返回数组或容器中最值元素(最小值、最大值),值和下标。
使用举例
#include<iostream>
#include<vector>
#include<algorithm>
using namespace std;
int main() {
/*数组初始化*/
vector<int> nums1;
int nums2[10] = { 0 };
for (int i = 0; i < 10; ++i) {
nums1.push_back(rand() % 100);
nums2[i] = rand() % 100;
}
for (auto i : nums1) cout << i << " ";
cout << endl;
for (auto i : nums2) cout << i << " ";
cout << endl;
/*求数组最小值和最大值*/
cout << "vector的最小值为:" << *min_element(nums1.begin(), nums1.end()) << endl;
cout << "vector的最大值为:" << *max_element(nums1.begin(), nums1.end()) << endl;
cout << "数组的最小值为:" << *min_element(nums2, nums2 + 10) << endl;
cout << "数组的最大值为:" << *max_element(nums2, nums2 + 10) << endl;
/*求数组最大值和最小值所在下标*/
cout << "vector的最小值下标为:" << min_element(nums1.begin(), nums1.end()) - nums1.begin() << endl;
cout << "vector的最大值下标为:" << max_element(nums1.begin(), nums1.end()) - nums1.begin() << endl;
cout << "数组的最小值下标为:" << min_element(nums2, nums2 + 10) - nums2 << endl;
cout << "数组的最大值下标为:" << max_element(nums2, nums2 + 10) - nums2 << endl;
return 0;
}