The Grimoire of Nonsense

個人的なメモを残すブログ

STLのvectorで重複を削除

※この記事は下記の内容を参考に執筆させていただきました。
STLのvectorから同一要素を削除 - minus9d's diary


STLvectorにおいて重複を削除するにはsort()後にunique()し、erase()する必要がある。
この辺り関数化して用意しておくといいかも。


以下僕が書いたサンプルコード

#include <iostream>
#include <vector>
#include <algorithm>

using namespace std;

template < class T >
void vectorUnique( vector<T> &v )
{
	sort( v.begin(), v.end() );
	v.erase( unique( v.begin(), v.end() ), v.end() );
}

template < class T >
void showVector( vector<T> &v )
{
	for ( unsigned i = 0; i < v.size(); i++ )
		printf( "v[%d]: %d\n", i, v[i] );
}

int main()
{
	std::vector<int> v = { 1, 1, 4, 5, 1, 4, 8, 1, 0, 3, 6, 4, 3, 6, 4 };

	vectorUnique<int>( v );
	showVector<int>( v );

	return 0;
}