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