From 44e55538e4451f2970d325bf244f59289d0f5a9b Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E9=82=B9=E6=99=93=E8=88=AA?= <1210603696@qq.com> Date: Tue, 10 Mar 2015 10:23:03 +0800 Subject: [PATCH] =?UTF-8?q?=E5=AE=8C=E6=88=90generate=5Fn?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 1 + TinySTL/Algorithm.h | 9 +++++++++ TinySTL/Test/AlgorithmTest.cpp | 8 ++++++++ 3 files changed, 18 insertions(+) diff --git a/README.md b/README.md index ced52cf..7dee734 100644 --- a/README.md +++ b/README.md @@ -71,6 +71,7 @@ TinySTL * advance:100% * sort:100% * generate:100% + * generate_n:100% * distance:100% * 其他组件: * circular_buffer:100% diff --git a/TinySTL/Algorithm.h b/TinySTL/Algorithm.h index b1c8333..8f79f2c 100644 --- a/TinySTL/Algorithm.h +++ b/TinySTL/Algorithm.h @@ -544,6 +544,15 @@ namespace TinySTL{ *first = func(); } } + //********** [generate_n] ****************************** + //********* [Algorithm Complexity: O(N)] **************** + template + void generate_n(OutputIterator first, Size n, Generator gen){ + while (n--){ + *first = gen(); + ++first; + } + } //********** [distance] ****************************** //********* [Algorithm Complexity: O(N)] **************** template diff --git a/TinySTL/Test/AlgorithmTest.cpp b/TinySTL/Test/AlgorithmTest.cpp index b130c4a..fe1c09b 100644 --- a/TinySTL/Test/AlgorithmTest.cpp +++ b/TinySTL/Test/AlgorithmTest.cpp @@ -221,6 +221,14 @@ namespace TinySTL{ std::generate(std::begin(arr2), std::end(arr2), func); } assert(TinySTL::Test::container_equal(arr1, arr2)); + + int n1 = 0, n2 = 0; + auto gen1 = [&n1](){return n1++; }; + auto gen2 = [&n2](){return n2++; }; + int arr3[100], arr4[100]; + TinySTL::generate_n(arr3, 100, gen1); + std::generate_n(arr4, 100, gen2); + assert(TinySTL::Test::container_equal(arr3, arr4)); } void testDistance(){ TinySTL::list l(10, 0); -- GitLab