remove_copy関数は、元のソースの範囲から特定の値の要素を除いて、コピーを
行います。残りの要素の順番は変わりません。戻り値は新しい範囲の最後の次の要素をさしています。
template_Firstは、コピー元の範囲の最初の要素OutputIterator remove_copy( InputIterator _First, InputIterator _Last, OutputIterator _Result, const Type& _Val );
_Lastは、コピー元の範囲の最後の次
_Resultは、コピー先の最初の反復子
_Valは、範囲から取り除く値
では、さっそくプログラムを見てみましょう。
// removecopy01.cpp
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main()
{
vector<int> v1, v2(10);
vector<int>::iterator pv1, pv2;
int i;
for (i = 0; i < 10; i++)
v1.push_back(i);
cout << "v1----";
for (pv1 = v1.begin(); pv1 != v1.end(); pv1++)
cout << *pv1 << ", ";
cout << endl;
pv2 = v2.begin();
remove_copy(v1.begin(), v1.end(), pv2, 4);
cout << "v2----";
for (pv2 = v2.begin(); pv2 != v2.end(); pv2++)
cout << *pv2 << ", ";
cout << endl;
return 0;
}
では、結果を見てみましょう。
v2に4を除いて、順番通りコピーされています。
もちろん、コンテナだけでなく普通の配列に対しても使うことができます。
// removecopy02.cpp
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
int arr1[] = {0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, i;
static int arr2[10];
cout << "arr1---";
for (i = 0; i < 10; i++)
cout << arr1[i] << ", ";
cout << endl;
remove_copy(arr1, arr1 + 10, arr2, 3);
cout << "arr2---";
for (i = 0; i < 10; i++)
cout << arr2[i] << ", ";
cout << endl;
return 0;
}
ここで、
remove_copy(arr1, arr1 + 10, arr2, 3);の中のarr1 + 10は配列arr1の範囲の最後の次を指している点に注意してください。
実行結果は次のようになります。
Update Dec/04/2005 By Y.Kumei