How to remove an array of repeating elements?

Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allowed. https://blog.csdn.net/qiuchangyong/article/details/88920253

Possible in the actual development, encounter such a problem: there is a set of elements that make up the array, there are duplicate elements inside, which now want to remove duplicate elements that duplicate elements but one, how to do?

A straightforward idea is: use an array to store the results, for each element, check whether there is in the results array, if it does not exist placed, if there is ignored. Due to the size of the uncertain outcome of the array, with the STL vector storage more convenient. There is set in STL, i.e. set. To use it, we can better solve this problem.

#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;
}

 

Guess you like

Origin blog.csdn.net/qiuchangyong/article/details/88920253