C++提高编程 5 STL -常用算法(算术生成算法)

5.5  常用算术生成算法

注意:算术生成算法属于小型算法,使用时包含头文件为  #include<numeric>;

  accumulate    //计算容器元素累计总和

  fill        //向容器中添加元素

5.5.1  accumulate    //计算容器元素累计总和

函数原型:accumulate(iterator  beg,  iterator  end,  value);  //value起始值

//注意头文件是  #include<numeric>

#include<iostream>
using namespace std;
#include<vector>   
#include<numeric>

//常用算术生成算法 accumulate  


void test1()
{
    vector<int>v;
    for (int i = 0; i <= 100; i++)
    {
        v.push_back(i);
    }

    //参数3  起始累加值
    int total = accumulate(v.begin(), v.end(), 0);
    cout << "total = " << total << endl;                //total = 5050
//  int total = accumulate(v.begin(), v.end(), 1000);
//  cout << "total = " << total << endl;                //total = 6050
}

int main()
{
    test1();

    system("pause");
    return 0;
}

 

5.5.2  fill    //向容器中添加元素(replace)

函数原型:fill(iterator  beg,  iterator  end,  value);  //value填充的值

//有元素的情况下,所有数据都被修改

#include<iostream>
using namespace std;
#include<vector>   
#include<numeric>
#include<algorithm>

//常用算术生成算法  fill    //向容器中添加元素
void print1(int val)
{
    cout << val << " ";
}

void test1()
{
    vector<int>v;
    v.resize(10);            //指定大小后,默认填充0为初始值

    //后期重新填充
    fill(v.begin(), v.end(), 100);

    for_each(v.begin(), v.end(), print1);        //100 100 100 100 100 100 100 100 100 100
    cout << endl;


}

int main()
{
    test1();

    system("pause");
    return 0;
}

 

posted @ 2022-03-04 14:31  大白不会敲代码  阅读(100)  评论(0)    收藏  举报