码迷,mamicode.com
首页 > 编程语言 > 详细

C++ STD Gems06

时间:2019-12-30 17:11:19      阅读:72      评论:0      收藏:0      [点我收藏+]

标签:tab   table   tor   and   main   const   fill   gem   stream   

generate、generate_n、sample、iota

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

template<class Container>
void write_to_cout(Container& container, const char* delimiter = " ")
{
    std::copy(container.begin(), container.end(),
        std::ostream_iterator<typename Container::value_type>(std::cout, delimiter) );
}

void test0()
{

    std::vector<int> v(5, 10);
    v.reserve(10);

    std::fill_n(std::back_inserter(v), 10, 111);
    
    write_to_cout(v);
    std::cout << std::endl << std::endl;

    std::fill(v.begin() + 5, v.begin() + 7, 13);

    write_to_cout(v);
    std::cout << std::endl << std::endl;
}

void test1()
{
    std::vector<int> v(10);

    std::iota(v.begin(), v.end(), 0);

    write_to_cout(v);
    std::cout << std::endl << std::endl;
}

void test2()
{
    std::mt19937 rng( std::random_device{}() );
    std::uniform_int_distribution<int> d( 0,20 );

    std::vector<int> v;
    std::generate_n( std::back_inserter(v), 5, [val = 0]() mutable
    {
        const auto old = val;
        val += 3;
        return old;
    } );

    write_to_cout(v, " | ");
    std::cout << std::endl << std::endl;
}

void test3()
{
    std::vector<std::string> b = {"zero", "one", "two", "three", "four", "five", "six", "seven"};

    std::mt19937 rng( std::random_device{}() );

    write_to_cout(b);
    std::cout << std::endl;

    std::vector<std::string> v;
    // test algrithm c++17
    std::sample( b.begin(), b.end(), back_inserter(v), 4, rng );

    write_to_cout(v);
    std::cout << std::endl << std::endl;
}

int main()
{
    test0();
    test1();
    test2();
    test3();

    return 0;
}

C++ STD Gems06

标签:tab   table   tor   and   main   const   fill   gem   stream   

原文地址:https://www.cnblogs.com/codemeta-2020/p/12120495.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!