您的位置:首页 > 运维架构

泛型算法系列18:remove()&&remove_copy()

2009-08-15 14:25 477 查看
// remove.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <algorithm>
#include <vector>
#include <iostream>
/* ハ莎・
original vector sequence:
0 1 0 2 0 3 0 4 0 5
vector after remove, without applying erase():
1 2 3 4 5 3 0 4 0 5
vector after erase():
1 2 3 4 5
array after remove_copy():
1 2 3 4 5
*/
template<class _II, class _Ty> inline
_II my_find(_II _F, _II _L, const _Ty& _V)
{
for (; _F != _L; ++_F)
if (*_F == _V)
break;
return (_F);
}
template<class _II, class _OI, class _Ty> inline
_OI my_remove_copy(_II _F, _II _L, _OI _X, const _Ty& _V)
{
for (; _F != _L; ++_F)
if (!(*_F == _V))
*_X++ = *_F;
return (_X);
}

template<class _FI, class _Ty> inline
_FI my_remove(_FI _F, _FI _L, const _Ty& _V)
{
_F = find(_F, _L, _V);
if (_F == _L)
return (_F);
else
{
_FI _Fb = _F;
return (my_remove_copy(++_F, _L, _Fb, _V));
}
}

using namespace std;

void element_print(int val)
{
cout << val << " ";
}

int main(int argc, char* argv[])
{
int value = 0;
int ia[] = { 0, 1, 0, 2, 0, 3, 0, 4, 0, 5 };
vector< int > vec( ia, ia + 10 );
vector< int >::iterator vec_iter;

cout << "original vector sequence:/n";
for_each(vec.begin(), vec.end(), element_print);
cout << '/n';
vec_iter = my_remove( vec.begin(), vec.end(), value );
cout << "vector after remove, without applying erase():/n";
for_each(vec.begin(), vec.end(), element_print);
cout << '/n';

// erase the invalid elements from container
vec.erase( vec_iter, vec.end() );
cout << "vector after erase():/n";
for_each(vec.begin(), vec.end(), element_print);
cout << '/n';

int ia2[5];
vector< int > vec2( ia, ia+10 );
my_remove_copy( vec2.begin(), vec2.end(), ia2, value );
cout << "array after remove_copy():/n";
for_each(vec.begin(), vec.end(), element_print);
cout << '/n';

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: