From 7fef271c27c55ca6478240e68ca58bb61f5b9d65 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, 27 Jan 2015 11:09:01 +0800 Subject: [PATCH] =?UTF-8?q?=E5=AE=8C=E6=88=90advance?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- README.md | 1 + TinySTL/Algorithm.h | 29 +++++++++++++++++++++++++++++ TinySTL/Test/AlgorithmTest.cpp | 19 +++++++++++++++++++ TinySTL/Test/AlgorithmTest.h | 6 ++++++ 4 files changed, 55 insertions(+) diff --git a/README.md b/README.md index a5746b5..e9cca2e 100644 --- a/README.md +++ b/README.md @@ -68,6 +68,7 @@ TinySTL * equal:100% * is_permutation:100% * search:100% + * advance:100% * 其他组件: * circular_buffer:100% * bitmap:100% diff --git a/TinySTL/Algorithm.h b/TinySTL/Algorithm.h index 20e01f3..567eea5 100644 --- a/TinySTL/Algorithm.h +++ b/TinySTL/Algorithm.h @@ -441,6 +441,35 @@ namespace TinySTL{ } return last1; } + //********** [advance] ****************************** + //********* [Algorithm Complexity: O(N)] **************** + namespace { + template + void _advance(InputIterator& it, Distance n, input_iterator_tag){ + if (n < 0){ + while (n++){ + --it; + } + }else{ + while (n--){ + ++it; + } + } + } + template + void _advance(RandomIterator& it, Distance n, random_access_iterator_tag){ + if (n < 0){ + it -= (-n); + }else{ + it += n; + } + } + } + template + void advance(InputIterator& it, Distance n){ + typedef iterator_traits::iterator_category iterator_category; + _advance(it, n, iterator_category()); + } } diff --git a/TinySTL/Test/AlgorithmTest.cpp b/TinySTL/Test/AlgorithmTest.cpp index 7090d31..9bdd899 100644 --- a/TinySTL/Test/AlgorithmTest.cpp +++ b/TinySTL/Test/AlgorithmTest.cpp @@ -167,6 +167,24 @@ namespace TinySTL{ it = std::search(v.begin(), v.end(), needle2, needle2 + 3, [](int i, int j){return i == j; }); assert(it == v.end()); } + void testAdvance(){ + TinySTL::vector v; + TinySTL::list l; + for (auto i = 0; i != 10; ++i){ + v.push_back(i); + l.push_back(i); + } + auto vit = v.begin(); + auto lit = l.begin(); + + TinySTL::advance(vit, 5); + TinySTL::advance(lit, 5); + assert(*vit == 5 && *lit == 5); + + TinySTL::advance(vit, -5); + TinySTL::advance(lit, -5); + assert(*vit == 0 && *lit == 0); + } void testAllCases(){ @@ -188,6 +206,7 @@ namespace TinySTL{ testEqual(); testIsPermutation(); testSearch(); + testAdvance(); } } } \ No newline at end of file diff --git a/TinySTL/Test/AlgorithmTest.h b/TinySTL/Test/AlgorithmTest.h index f25dd9b..775acd0 100644 --- a/TinySTL/Test/AlgorithmTest.h +++ b/TinySTL/Test/AlgorithmTest.h @@ -10,8 +10,13 @@ #include #include #include +#include #include +#include "../List.h" +#include "../Vector.h" + + namespace TinySTL{ namespace AlgorithmTest{ void testFill(); @@ -32,6 +37,7 @@ namespace TinySTL{ void testEqual(); void testIsPermutation(); void testSearch(); + void testAdvance(); void testAllCases(); }