美文网首页
黑马C++视频笔记《STL之简单算术算法》

黑马C++视频笔记《STL之简单算术算法》

作者: 井底蛙蛙呱呱呱 | 来源:发表于2021-01-28 00:32 被阅读0次
/* 算术生成算法属于小型算法,使用时包含的头文件为`<numeric>`
 *
 * accumulate
 * 计算区间内容器元素累计总和;
 * 函数原型:`accumulate(iterator beg, iterator end, value);`
 *  - iterator beg 和 iterator end 指定累加的元素范围;
 *  - val指定起始值,即后面的累加都是在这个基础上进行累加的;
 *
 *
 * fill
 * 向容器指定区间中填充特定元素;
 * 函数原型:`fill(iterator beg, iterator end, value);`
 *  - iterator beg 和 iterator end 指定填充的元素范围;
 *  - value,指定填充的值;
 */

一个🌰:

#include <iostream>
#include <string>
#include <ctime>
#include <vector>
#include <algorithm>
#include <random>
#include <numeric>

using namespace std;


void CreateVec(vector<int> &v){
    // srand((unsigned int)time(NULL)); 旧版生成随机数方法,弃用
    std::random_device rd; // Will be used to obtain a seed for the random number engine
    std::mt19937 gen(rd()); // Standard mersenne_twister_engine seeded with rd()
    std::uniform_int_distribution<> dist(0, 1000);
    for(int i=0; i<10; i++){
        int a  = dist(gen); // 使用新的产生随机数的方式
        v.push_back(a);
    }
}

class myPrint{
public:
    void operator()(int val){
        cout << val << " ";
    }
};

int main(){
    vector<int> v1;
    vector<int> v2;
    CreateVec(v1);


    cout << "填充前:"<< endl;
    for_each(v1.begin(), v1.end(), myPrint());
    cout << endl;
    int tot;
    tot = accumulate(v1.begin(), v1.end(), 0);
    cout << "TOT = " << tot << endl;

    cout << "填充后:"<< endl;
    fill(v1.begin(), v1.end(), 100);
    for_each(v1.begin(), v1.end(), myPrint());
    cout << endl;
    tot = accumulate(v1.begin(), v1.end(), 0);
    cout << "TOT = " << tot << endl;
}

输出

填充前:
11 399 179 250 382 161 733 857 951 424 
TOT = 4347
填充后:
100 100 100 100 100 100 100 100 100 100 
TOT = 1000

网友评论

      本文标题:黑马C++视频笔记《STL之简单算术算法》

      本文链接:https://www.haomeiwen.com/subject/bonmzktx.html