完成advance

This commit is contained in:
邹晓航
2015-01-27 11:09:01 +08:00
parent 4c322450c6
commit 7fef271c27
4 changed files with 55 additions and 0 deletions

View File

@@ -68,6 +68,7 @@ TinySTL
* equal100% * equal100%
* is_permutation100% * is_permutation100%
* search100% * search100%
* advance100%
* 其他组件: * 其他组件:
* circular_buffer100% * circular_buffer100%
* bitmap100% * bitmap100%

View File

@@ -441,6 +441,35 @@ namespace TinySTL{
} }
return last1; return last1;
} }
//********** [advance] ******************************
//********* [Algorithm Complexity: O(N)] ****************
namespace {
template<class InputIterator, class Distance>
void _advance(InputIterator& it, Distance n, input_iterator_tag){
if (n < 0){
while (n++){
--it;
}
}else{
while (n--){
++it;
}
}
}
template<class RandomIterator, class Distance>
void _advance(RandomIterator& it, Distance n, random_access_iterator_tag){
if (n < 0){
it -= (-n);
}else{
it += n;
}
}
}
template <class InputIterator, class Distance>
void advance(InputIterator& it, Distance n){
typedef iterator_traits<InputIterator>::iterator_category iterator_category;
_advance(it, n, iterator_category());
}
} }

View File

@@ -167,6 +167,24 @@ namespace TinySTL{
it = std::search(v.begin(), v.end(), needle2, needle2 + 3, [](int i, int j){return i == j; }); it = std::search(v.begin(), v.end(), needle2, needle2 + 3, [](int i, int j){return i == j; });
assert(it == v.end()); assert(it == v.end());
} }
void testAdvance(){
TinySTL::vector<int> v;
TinySTL::list<int> 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(){ void testAllCases(){
@@ -188,6 +206,7 @@ namespace TinySTL{
testEqual(); testEqual();
testIsPermutation(); testIsPermutation();
testSearch(); testSearch();
testAdvance();
} }
} }
} }

View File

@@ -10,8 +10,13 @@
#include <cctype> #include <cctype>
#include <cstring> #include <cstring>
#include <cassert> #include <cassert>
#include <list>
#include <vector> #include <vector>
#include "../List.h"
#include "../Vector.h"
namespace TinySTL{ namespace TinySTL{
namespace AlgorithmTest{ namespace AlgorithmTest{
void testFill(); void testFill();
@@ -32,6 +37,7 @@ namespace TinySTL{
void testEqual(); void testEqual();
void testIsPermutation(); void testIsPermutation();
void testSearch(); void testSearch();
void testAdvance();
void testAllCases(); void testAllCases();
} }