繰り返し要素の配列を削除する方法?

免責事項:この記事はブロガーオリジナル記事ですが、許可ブロガーなく再生してはなりません。https://blog.csdn.net/qiuchangyong/article/details/88920253

実際の開発で使用可能な、このような問題が発生します。配列を構成する要素の集合であり、重複要素が内部にありますが、今の要素を複製するが、1つ、どのように行うために、重複要素を削除しますか?

単純な考え方は次のとおりですが無視される場合には、配置が存在しない場合、結果の配列に存在するか否かを確認し、各要素について、結果を格納する配列を使用します。より便利なSTLベクトル記憶を持つ配列の不確実な成果の大きさに起因します。そこは、STL、すなわちセットに設定されています。これを使用するには、私たちはより良い、この問題を解決することができます。

#include <iostream>
#include <vector>
#include <set>

using namespace std;

// Removes duplicate elements in a given vector.
template<typename _Tp>
inline vector<_Tp> remove_dups(const vector<_Tp>& src) {
	typedef typename set<_Tp>::const_iterator constSetIterator;
	typedef typename vector<_Tp>::const_iterator constVecIterator;
	set<_Tp> set_elems;
	for (constVecIterator it = src.begin(); it != src.end(); ++it)
		set_elems.insert(*it);
	vector<_Tp> elems;
	for (constSetIterator it = set_elems.begin(); it != set_elems.end(); ++it)
		elems.push_back(*it);
	return elems;
}

int main()
{
	// give an array of elements with repeated ones
	vector<int> src{ 1, 2, 2, 3, 5, 4, 3, 2, 1, 2, 6, 4, 3, 6, 5 };	
	vector<int> result = remove_dups(src);
	for (unsigned int i = 0; i < result.size(); i++) {
		cout << result[i] << endl;
	}

    return 0;
}

 

おすすめ

転載: blog.csdn.net/qiuchangyong/article/details/88920253