#include<numeric>//算術生成算法頭文件
要加的頭文件#include<numeric>
accumulate
?是 C++ 標準庫中的一個算法函數,用于計算給定范圍內的數值之和,它位于?<numeric>
?頭文件中。它的函數原型如下:
template <class InputIt, class T> T accumulate(InputIt first, InputIt last, T init);
其中,InputIt
?是一個迭代器類型,表示輸入范圍的起始和結束位置;T
?是要累加的數值類型;init
?是初始值,即累加的初始結果。
accumulate
?函數會將輸入范圍?[first, last)
?中的元素依次累加到初始值上,并返回最終的累加結果。累加過程中,會使用元素的加法運算符進行累加。
void test01()
{vector<int>v = { 10,20,30 };int n=accumulate(v.begin(), v.end(), 0);//總和上再加0cout << n << endl;
}
//操作對象
class maker
{
public:maker(int age){this->age = age;}
public:int age;
};
struct myfunc
{int operator()(int val, maker& m){return val + m.age;}
};
void test02()
{vector<maker>v = { maker(10),maker(20),maker(30) };int a=accumulate(v.begin(), v.end(), 0, myfunc());cout << a << endl;
}
fill
?是 C++ 標準庫中的一個算法函數,用于將給定值賦給指定范圍內的所有元素。它位于?<algorithm>
?頭文件中。fill
?的函數原型如下:
template <class ForwardIt, class T> void fill(ForwardIt first, ForwardIt last, const T& value);
其中,ForwardIt
?是一個前向迭代器類型,表示要填充的范圍的起始和結束位置;T
?是要賦給元素的值類型;value
?是要填充的值。
fill
?函數會將輸入范圍?[first, last)
?中的所有元素都賦值為?value
。
void test03()
{vector<int>v;v.resize(10);fill(v.begin(), v.end(), 100);for_each(v.begin(), v.end(), [](int val)->void {cout << val << " "; });
}