min_element
时间: 2023-09-10 15:07:17 浏览: 48
The `min_element` function is a standard library algorithm in C++ that finds the smallest element in a range of elements. It takes two arguments - the beginning and end iterators of the range - and returns an iterator pointing to the smallest element.
Here's an example usage of `min_element` to find the smallest element in a vector of integers:
```c++
#include <iostream>
#include <vector>
#include <algorithm>
int main() {
std::vector<int> nums = {5, 2, 8, 1, 9, 4};
auto min_it = std::min_element(nums.begin(), nums.end());
std::cout << "The smallest element is " << *min_it << "\n";
return 0;
}
```
This program will output: `The smallest element is 1`.
相关问题
c++min_element
`min_element`是C++ STL中的一个算法函数,在头文件`<algorithm>`中声明。它用于查找给定范围内的最小元素,并返回指向该元素的迭代器。
`min_element`的语法如下:
```c++
template<class ForwardIt>
ForwardIt min_element(ForwardIt first, ForwardIt last);
```
其中,`first`和`last`是表示要查找的范围的迭代器,`ForwardIt`是迭代器类型。
举个例子,如果要在一个整数数组中查找最小值,可以这样使用`min_element`函数:
```c++
#include <algorithm>
#include <iostream>
#include <vector>
int main() {
std::vector<int> v {3, 1, 4, 1, 5, 9, 2, 6};
auto it = std::min_element(v.begin(), v.end());
std::cout << "The minimum element is " << *it << '\n';
return 0;
}
```
这个程序输出:
```
The minimum element is 1
```
因为数组中最小的元素是1。
std::min_element
`std::min_element` 是 C++ STL 中的一个函数,它用于查找迭代器范围内的最小值,并返回指向该最小值的迭代器。
例如,对于一个 vector<int> v,若要查找 v 中的最小值,则可以使用以下代码:
```c++
auto min_it = std::min_element(v.begin(), v.end());
```
其中,`v.begin()` 和 `v.end()` 分别是指向 v 的开头和结尾的迭代器。`min_it` 是一个指向最小值的迭代器,可以通过 `*min_it` 获得最小值。
`std::min_element` 还可以接受一个可调用对象,用于自定义比较规则。例如,若要查找 v 中绝对值最小的值,则可以使用以下代码:
```c++
auto abs_min_it = std::min_element(v.begin(), v.end(), [](int a, int b) {
return std::abs(a) < std::abs(b);
});
```
其中,`[](int a, int b) { return std::abs(a) < std::abs(b); }` 是一个 lambda 函数,用于定义比较规则。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)