数组或vector最大值最小值
我们介绍库函数max_element() 及 min_element(),二者返回的都是迭代器
头文件:< algorithm >
1.求数组的最大值或最小值
1)vector容器
vector<int> nums = {1,2,3,8,0,33,11,9};
int max_num = *max_element(nums.begin(), nums.end()); //获取最大值
int min_num = *min_element(nums.begin(), nums.end());//获取最小值
2)普通数组
int nums[8] = {1,2,3,8,0,33,11,9};
int max_num = *max_element(nums, nums + 8);
int min_num = *min_element(nums, nums + 8);
2.求数组最大值最小值对应的下标
1)vector容器
vector<int> nums = {1,2,3,8,0,33,11,9};
int max_num_index = max_element(nums.begin(), nums.end()) - nums.begin(); //获取最大值对应的下标
int min_num_index = min_element(nums.begin(), nums.end()) - nums.begin();//获取最小值对应的下标
2)普通数组
int nums[8] = {1,2,3,8,0,33,11,9};
int max_num_index = max_element(nums, nums + 8) - nums;
int min_num_index = min_element(nums, nums + 8) - nums;