【C/C++】標準庫之 numeric
阿新 • • 發佈:2018-12-31
顧名思義, numeric
是一個用於數值計算的小庫.
Generalized numeric operations
This header describes a set of algorithms to perform certain operations on sequences of numeric values. Due to their flexibility, they can also be adapted for other kinds of sequences.
比較常用的就一個累加函式 accumulate
, 定義和實現如下
template <class InputIterator , class T>
T accumulate (InputIterator first, InputIterator last, T init)
{
while (first!=last) {
init = init + *first; // or: init=binary_op(init,*first) for the binary_op version
++first;
}
return init;
}
場景, 計算平均值
#include <numeric>
...
std::vector<float> scores(3) ;
scores.push_back(1.2);
scores.push_back(2.8);
scores.push_back(3.5);
float mean = std::accumulate(scores.begin(), scores.end(), 0.0) / scores.size();
...
此外, 還有幾個函式, 也比較有意思
inner_product
, 計算兩個向量的內積
template <class InputIterator1, class InputIterator2, class T>
T inner_product (InputIterator1 first1, InputIterator1 last1,
InputIterator2 first2, T init)
{
while (first1!=last1) {
init = init + (*first1)*(*first2);
// or: init = binary_op1 (init, binary_op2(*first1,*first2));
++first1; ++first2;
}
return init;
}
---
int init = 100;
int series1[] = {10,20,30};
int series2[] = {1,2,3};
std::cout << "using default inner_product: ";
std::cout << std::inner_product(series1,series1+3,series2,init);
std::cout << '\n';
=> using default inner_product: 240
adjacent_difference
: 計算臨差
template <class InputIterator, class OutputIterator>
OutputIterator adjacent_difference (InputIterator first, InputIterator last,
OutputIterator result)
{
if (first!=last) {
typename iterator_traits<InputIterator>::value_type val,prev;
*result = prev = *first;
while (++first!=last) {
val = *first;
*++result = val - prev; // or: *++result = binary_op(val,prev)
prev = val;
}
++result;
}
return result;
}
---
int val[] = {1,2,3,5,9,11,12};
int result[7];
std::adjacent_difference (val, val+7, result);
std::cout << "using default adjacent_difference: ";
=> using default adjacent_difference: 1 1 1 2 4 2 1
partial_sum
:計算區域性累加和
template <class InputIterator, class OutputIterator>
OutputIterator partial_sum (InputIterator first, InputIterator last,
OutputIterator result)
{
if (first!=last) {
typename iterator_traits<InputIterator>::value_type val = *first;
*result = val;
while (++first!=last) {
val = val + *first; // or: val = binary_op(val,*first)
*++result = val;
}
++result;
}
return result;
}
---
int val[] = {1,2,3,4,5};
int result[5];
std::partial_sum (val, val+5, result);
std::cout << "using default partial_sum: ";
=> using default partial_sum: 1 3 6 10 15
iota
: Store increasing sequence 生成遞增數列, 很簡單的功能, 很奇怪的名字.
template <class ForwardIterator, class T>
void iota (ForwardIterator first, ForwardIterator last, T val)
{
while (first!=last) {
*first = val;
++first;
++val;
}
}
---
int numbers[10];
std::iota (numbers,numbers+10,100);
std::cout << "numbers:";
=> numbers: 100 101 102 103 104 105 106 107 108 109