如何去除一个数组中的重复元素?

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qiuchangyong/article/details/88920253

可能在实际开发中,会遇到这样的一个问题:有一组元素构成的数组,里面存在重复的元素,现在要去除其中重复的元素,即重复的元素只保留一个,如何做到?

一个直接的想法是:用一个数组存放结果,对每个元素,检查其在结果数组中是否存在,如果不存在则放入,如果存在则忽略。由于不确定结果数组的大小,用STL vector存放比较方便。在STL中有个set,即集合。用上它,就能较好地解决这个问题。

#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