第13题写c++代码如何实现?
时间: 2024-04-12 20:32:14 浏览: 34
以下是用C++实现求无序数组的最小最大值的代码:
```cpp
#include <iostream>
#include <vector>
#include <limits>
std::pair<int, int> findMinMax(const std::vector<int>& nums) {
int min = std::numeric_limits<int>::max();
int max = std::numeric_limits<int>::min();
for (int i = 0; i < nums.size(); i++) {
if (nums[i] < min) {
min = nums[i];
}
if (nums[i] > max) {
max = nums[i];
}
}
return std::make_pair(min, max);
}
int main() {
std::vector<int> nums = {9, 5, 2, 8, 1, 7, 4};
std::pair<int, int> result = findMinMax(nums);
std::cout << "Min: " << result.first << std::endl;
std::cout << "Max: " << result.second << std::endl;
return 0;
}
```
该代码使用了一个循环遍历数组,通过比较当前元素与最小值和最大值,更新min和max的值。最后返回一个pair,包含最小值和最大值。在main函数中,我们使用了一个示例数组来测试该函数,并输出最小值和最大值。
阅读全文
相关推荐















