c++ 获取vector中最大最小值
时间: 2024-05-05 10:14:00 浏览: 15
以下是两种C++获取vector中最最小值的方法:
1. 使用`max_element`和`min_element`函数[^1]:
```cpp
#include <vector>
#include <algorithm>
std::vector<double> a;
double amax = *std::max_element(a.begin(), a.end()); // 最大值
double amin = *std::min_element(a.begin(), a.end()); // 最小值
```
2. 使用循环遍历的方式获取最大最小值:
```cpp
#include <vector>
std::vector<double> a;
double amax = a; // 假设第一个元素为最大值
double amin = a; // 假设第一个元素为最小值
for (int i = 1; i < a.size(); i++) {
if (a[i] > amax) {
amax = a[i];
}
if (a[i] < amin) {
amin = a[i];
}
}
```
相关问题
c++ 找出vector中的最小值
你可以使用 `std::min_element` 函数来找出 vector 中的最小值。
下面是一个示例代码:
```c++
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> numbers = {4, 2, 8, 5, 1, 7, 6, 3};
auto min_element = std::min_element(numbers.begin(), numbers.end());
std::cout << "The minimum element is " << *min_element << std::endl;
return 0;
}
```
在上面的代码中,我们使用 `std::min_element` 函数来找出 vector 中的最小值,并且使用 `*min_element` 来获取该值。输出结果应该为:
```
The minimum element is 1
```
vector最大最小值
要求计算vector的最大值和最小值,可以使用C++标准库中的<algorithm>头文件中的max_element()和min_element()函数。这两个函数分别返回vector中的最大值和最小值的迭代器。
首先,包含<vector>和<algorithm>头文件:
#include <vector>
#include <algorithm>
接下来,定义一个vector并填充数据:
vector<double> a;
// 假设a已经填充了一些双精度浮点数
然后,使用max_element()和min_element()函数找到最大值和最小值的迭代器:
auto maxIter = max_element(a.begin(), a.end());
auto minIter = min_element(a.begin(), a.end());
最后,通过解引用迭代器获取最大值和最小值:
double maxVal = *maxIter;
double minVal = *minIter;
这样,maxVal和minVal就分别是vector中的最大值和最小值了。<span class="em">1</span><span class="em">2</span><span class="em">3</span>
#### 引用[.reference_title]
- *1* *2* *3* [C++:求vector容器中最大最小值的位置](https://blog.csdn.net/qq_44894692/article/details/115607521)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_2"}}] [.reference_item style="max-width: 100%"]
[ .reference_list ]