プログラミング道場 ACM/ICPC

要素の削除

最終更新:

kit

- view
だれでも歓迎! 編集
/*
	template<class _FwdIt, class _Ty>
	_FwdIt remove(_FwdIt _First, _FwdIt _Last, const _Ty& _Val)

	template<class _FwdIt, class _Pr>
 	_FwdIt remove_if(_FwdIt _First, _FwdIt _Last, _Pr _Pred)
*/

#include <algorithm>
#include <iostream>
#include <functional>
#include <iterator>
#include <vector>

using namespace std;

int main()
{
	vector<int> a;

	// a = {0,1,0,3...0,8,0,9}
	for( int i = 0; i < 10; ++i )
		a.push_back( i&1 ? i : 0 );

	// 0,1,0,3,0,5,0,7,0,9,
	copy( a.begin(),a.end(), ostream_iterator<int>(cout,",") );
	cout << endl;

	// 要素0を取り除く
	a.erase( remove(a.begin(),a.end(),0), a.end() );

	// 1,3,5,7,9,
	copy( a.begin(),a.end(), ostream_iterator<int>(cout,",") );
	cout << endl;

	a.clear();

	// a = {1,2...9,10}
	for( int i = 0; i < 10; ++i )
		a.push_back(i+1);

	// 1,2,3,4,5,6,7,8,9,10
	copy( a.begin(),a.end(), ostream_iterator<int>(cout,",") );
	cout << endl;

	//奇数を取り除く
	a.erase( remove_if( a.begin(), a.end(), bind2nd(modulus<int>(),2) ), a.end() );

	// 2.4.6.8.10
	copy( a.begin(),a.end(), ostream_iterator<int>(cout,",") );
	cout << endl;

	return 0;
}
ウィキ募集バナー