完成copy算法

This commit is contained in:
邹晓航
2015-03-11 12:41:50 +08:00
parent 44e55538e4
commit e59e50132c
4 changed files with 59 additions and 0 deletions

View File

@@ -73,6 +73,7 @@ TinySTL
* generate100%
* generate_n100%
* distance100%
* copy100%
* 其他组件:
* circular_buffer100%
* bitmap100%

View File

@@ -576,6 +576,45 @@ namespace TinySTL{
typedef typename iterator_traits<Iterator>::iterator_category iterator_category;
return _distance(first, last, iterator_category());
}
//********** [copy] ******************************
//********* [Algorithm Complexity: O(N)] ****************
template<class InputIterator, class OutputIterator>
OutputIterator __copy(InputIterator first, InputIterator last, OutputIterator result, _true_type){
auto dist = distance(first, last);
memcpy(result, first, sizeof(*first) * dist);
advance(result, dist);
return result;
}
template<class InputIterator, class OutputIterator>
OutputIterator __copy(InputIterator first, InputIterator last, OutputIterator result, _false_type){
while (first != last){
*result = *first;
++result;
++first;
}
return result;
}
template<class InputIterator, class OutputIterator, class T>
OutputIterator _copy(InputIterator first, InputIterator last, OutputIterator result, T*){
typedef typename TinySTL::_type_traits<T>::is_POD_type is_pod;
return __copy(first, last, result, is_pod());
}
template <class InputIterator, class OutputIterator>
OutputIterator copy(InputIterator first, InputIterator last, OutputIterator result){
return _copy(first, last, result, value_type(first));
}
template<>
inline char *copy(char *first, char *last, char *result){
auto dist = last - first;
memcpy(result, first, sizeof(*first) * dist);
return result + dist;
}
template<>
inline wchar_t *copy(wchar_t *first, wchar_t *last, wchar_t *result){
auto dist = last - first;
memcpy(result, first, sizeof(*first) * dist);
return result + dist;
}
}

View File

@@ -242,6 +242,23 @@ namespace TinySTL{
assert(TinySTL::distance(l.begin(), lit) == 5);
assert(TinySTL::distance(v.begin(), vit) == 5);
}
void testCopy(){
char arr1[] = "hello", res1[6] = { 0 };
TinySTL::copy(std::begin(arr1), std::end(arr1), res1);
assert(TinySTL::Test::container_equal(arr1, res1));
wchar_t arr2[] = L"hello", res2[6] = { 0 };
TinySTL::copy(std::begin(arr2), std::end(arr2), res2);
assert(TinySTL::Test::container_equal(arr2, res2));
int arr3[10] = { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 }, res3[10] = { 0 };
TinySTL::copy(std::begin(arr3), std::end(arr3), res3);
assert(TinySTL::Test::container_equal(arr3, res3));
std::string arr4[3] = { "1", "2", "3" }, res4[3];
TinySTL::copy(std::begin(arr4), std::end(arr4), res4);
assert(TinySTL::Test::container_equal(arr4, res4));
}
void testAllCases(){
testFill();
@@ -266,6 +283,7 @@ namespace TinySTL{
testSort();
testGenerate();
testDistance();
testCopy();
}
}
}

View File

@@ -44,6 +44,7 @@ namespace TinySTL{
void testSort();
void testGenerate();
void testDistance();
void testCopy();
void testAllCases();
}