最大/最小操作

iota()

头文件
< numeric >
用从起始值开始连续递增的值填充一个范围
函数
void iota( ForwardIt first, ForwardIt last, T value );
以始于 value 并重复地求值 ++value 的顺序递增值填充范围 [first, last) 。

代码演示

#include<iostream>
#include<vector>
#include<cstdio>
#include<string>
#include <list>
#include <numeric>
using namespace std;
int main() {
    list<int> l(10);
    iota(l.begin(), l.end(), -4);
    for (auto i : l) cout << i << " ";
    cout << endl;
    vector<list<int>::iterator > v(l.size());
    iota(v.begin(), v.end(), l.begin());
    for (auto i : v) cout << *i << " ";
    cout << endl;
    return 0;
}

运行结果

-4 -3 -2 -1 0 1 2 3 4 5 
-4 -3 -2 -1 0 1 2 3 4 5 ```

accumulate()

对一个范围内的元素求和
头文件
< numeric >
函数

template< class InputIt, class T >
T accumulate( InputIt first, InputIt last, T init );

参数
first, last - 要求和的元素范围
init - 和的初值

 std::vector<int> v{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
 int sum = std::accumulate(v.begin(), v.end(), 0);

max_element()

template< class ForwardIt, class Compare >

ForwardIt max_element(ForwardIt first, ForwardIt last, Compare comp );

寻找范围 [first, last) 中的最大元素。

 std::vector<int> v{ 3, 1, -14, 1, 5, 9 }; 
 result = std::max_element(v.begin(), v.end());
 result = std::max_element(v.begin(), v.end(), abs_compare);//abs_compare是自定义的比较函数
 

min_element()

返回范围内的最小元素

minmax_element()

template< class ForwardIt, class Compare >
constexpr std::pair<ForwardIt,ForwardIt>
minmax_element( ForwardIt first, ForwardIt last, Compare comp );

寻找范围 [first, last) 中最小和最大的元素。

#include <algorithm>
#include <iostream>
#include <vector>
 
int main()
{
    std::vector<int> v = { 3, 9, 1, 4, 2, 5, 9 };
 
    auto result = std::minmax_element(v.begin(), v.end());
    std::cout << "min element at: " << (result.first - v.begin()) << '\n';
    std::cout << "max element at: " << (result.second - v.begin()) << '\n';
}
min element at: 2
max element at: 6
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值