1 Replies - 1948 Views - Last Post: 13 February 2012 - 03:00 AM

#1 sarmanu   User is offline

  • D.I.C Lover
  • member icon

Reputation: 967
  • View blog
  • Posts: 2,362
  • Joined: 04-December 09

Remove duplicates from a STL vector

Posted 31 March 2010 - 08:32 AM

Description: Nothing special required.
#include <iostream>
#include <set>
#include <vector>
#include <algorithm>

// Needed for std::set 
template <typename T>
struct Compare
{
        // Add elements to set only if 
	bool operator()(const T n1, const T n2) const
	{
		return n1 != n2;
	}
};

template <typename T>
std::vector<T> removed_duplicates(const std::vector<T> &vect)
{
        // Declare a set which will contain the non-duplicates
        // from vect
	std::set<T, Compare<T> > non_dups;

        // Insert the non-duplicates to the set
	for (size_t i = 0; i < vect.size(); i++)
		non_dups.insert(vect[i]);

	std::vector<T> result; // Holds the result
        // Declare an iterator to "set", and copy the elements from
        // non_dups to result
	std::set<T, Compare<T> >::iterator itr = non_dups.begin();
	while (itr != non_dups.end())
	{
		result.push_back(*itr);
		++itr;
	}

        // Reverse the result to prevent the order changing
        // of elements in the original vector
	std::reverse(result.begin(), result.end());
	return result;
}

// Generic output using a const_iterator
template <typename T>
void output(const std::vector<T> &vect)
{
	std::vector<T>::const_iterator citer = vect.begin();
	for (citer; citer != vect.end(); ++citer)
		std::cout << *citer << " ";
	std::cout << std::endl;
}

int main()
{
        // Declare a vector an assign some data to it
	std::vector<int> vect;
	vect.push_back(13);
	vect.push_back(20);
	vect.push_back(20);
	vect.push_back(13);
	vect.push_back(10);
	vect.push_back(20);
	vect.push_back(3);
	vect.push_back(3);
        // rd is the vector holding the original vector ("vect")
        // but with non-duplicates. As you can see, the removed_duplicates
        // function is templated, so you can pass an array of any
        // primitive data type to it.
	std::vector<int> rd = removed_duplicates<int>(vect);
	output<int>(rd); // Output the vector

        // Pause the console so the user can see the output
	std::cin.get();
	return 0;
}


Is This A Good Question/Topic? 0
  • +

Replies To: Remove duplicates from a STL vector

#2 Karel-Lodewijk   User is offline

  • D.I.C Addict
  • member icon

Reputation: 454
  • View blog
  • Posts: 864
  • Joined: 17-March 11

Re: Remove duplicates from a STL vector

Posted 13 February 2012 - 03:00 AM

std::sort followed by std::unique and an erase will accomplish the same thing.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1