[c++基础]标准算法

二次信任 提交于 2019-12-01 05:41:45

fill fill_n generate and generate_n

//fig16_01.cpp
//fill fill_n generate and generate_n
#include <iostream>
#include <algorithm>
#include <array>
#include <iterator>

using namespace std;
char nextLetter()
{
    static char letter = 'A';//static
    return letter++;
}
int main()
{
    array<char, 10>chars;
    ostream_iterator<char> output(cout, " ");

    fill(chars.begin(), chars.end(), '5');

    //array有10个值,所以填充10个5
    cout << "\nAfter filling withs 5:";
    copy(chars.cbegin(), chars.cend(), output);
    cout << endl;//5 5 5 5 5 5 5 5 5 5

    //从开始处,填充5个A,改变了原先的值
    fill_n(chars.begin(), 5, 'A');
    cout << "\nAfter fill_n withs A:";
    copy(chars.cbegin(), chars.cend(), output);
    cout << endl;//A A A A A 5 5 5 5 5


    //gernerate 指定的填充函数必须无参
    //用指定的填充函数取填充
    generate(chars.begin(), chars.end(), nextLetter);
    cout << "\nAfter generate withs nextLetter funciton:";
    copy(chars.cbegin(), chars.cend(), output);
    cout << endl;//A B C D E F G H I J

    //从开始处 用指定的填充函数填充5个 
    generate_n(chars.begin(), 5, nextLetter);
    cout << "\nAfter generate_n withs nextLetter funciton:";
    copy(chars.cbegin(), chars.cend(), output);
    cout << endl;//K L M N O F G H I J

    return 0;
}

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!