c++min_element
时间: 2023-08-01 22:12:02 浏览: 174
`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。
相关问题
minmax_element minmax_element
`minmax_element` 是 C++ STL 中的一个函数,用于查找给定范围内的最小值和最大值。它的用法如下:
```cpp
template<class ForwardIt>
std::pair<ForwardIt,ForwardIt> minmax_element(ForwardIt first, ForwardIt last);
```
其中 `first` 和 `last` 分别是要查找的范围的起始和终止迭代器,函数返回一个 `pair` 类型的值,其中 `pair.first` 是最小值的迭代器,`pair.second` 是最大值的迭代器。
例如,以下代码演示了如何使用 `minmax_element` 查找数组 `arr` 中的最小值和最大值:
```cpp
#include <iostream>
#include <algorithm>
int main()
{
int arr[] = { 5, 3, 1, 4, 2 };
auto result = std::minmax_element(arr, arr + 5);
std::cout << "Min element is: " << *result.first << "\n";
std::cout << "Max element is: " << *result.second << "\n";
return 0;
}
```
输出:
```
Min element is: 1
Max element is: 5
```
min_element
The `min_element` function is a standard library algorithm in C++ that returns an iterator pointing to the smallest element in a range of elements. It takes two arguments: a starting iterator and an ending iterator that define the range of elements to search through.
Here is an example usage of the `min_element` function:
```
#include <iostream>
#include <algorithm>
#include <vector>
int main() {
std::vector<int> vec {5, 2, 9, 1, 7};
auto min_it = std::min_element(vec.begin(), vec.end());
std::cout << "The minimum element is: " << *min_it << std::endl;
return 0;
}
```
In this example, we create a vector of integers and use the `min_element` function to find the smallest element in that vector. The `min_it` variable is an iterator that points to the minimum element, which we then dereference and print to the console. The output of this program would be:
```
The minimum element is: 1
```
阅读全文