Need help with STL (?)

T

Tom

How can you delete doubles of an element in a vector, all elements
check and then delete the extra ones that are in the list.
 
J

Jeff Schwab

Tom said:
How can you delete doubles of an element in a vector, all elements
check and then delete the extra ones that are in the list.

// You'd probably be better off working with iterators only
// (instead of containers), but here's the general idea.

template< typename C >
void remove_duplicates( C& c )
{

std::map<typename C::element_type, bool> seen;
C unique_elements;
C::const_iterator p = c.begin( );

while( p != c.end( ) )
{
if( ! seen[ *p ] )
{
unique_elements.push_back( *p );
seen[ *p ] = true;
}

++p;
}

orig.swap( unique_elements );
}
 
M

M. Akkerman

How can you delete doubles of an element in a vector, all elements
check and then delete the extra ones that are in the list.

If you're going to erase, insert stuff at random places it's better to
use a list then a vector.
 
M

Michael Mellor

Tom said:
How can you delete doubles of an element in a vector, all elements
check and then delete the extra ones that are in the list.

If you are willing to sort the vector then the following works well.

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

int main ( ) {
// Initialise vector
int list[] = { 1,2,3,4,5,4,3,2,1,2,3,4,5 };
std::vector<int> a ( list, list + sizeof(list)/sizeof(int) );

// Print contents
std::copy ( a.begin(), a.end(),
std::eek:stream_iterator<int>(std::cout," "));
std::cout << '\n';

// Unique requires a sorted list
std::sort ( a.begin(), a.end() );

// Move duplicates to end of list
std::vector<int>::iterator end = std::unique ( a.begin(), a.end() );

// Erase duplicates
a.erase ( end, a.end() );

// Print new contents
std::copy ( a.begin(), a.end(),
std::eek:stream_iterator<int>(std::cout," "));
std::cout << '\n';
}
 
C

Christine

I answered another question of yours with a similar suggestion ... unless
you must use a vector for some reason, consider using an std::set. On
insert, it will return an error if the element already exists. Then you can
choose to delete the existing one and re-do the insert. (Some
implementations of std::set use operator[] to automatically replace an
existing element with the new one, but I'm not sure if that's standard for
all implementations.)

Christine
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,009
Latest member
GidgetGamb

Latest Threads

Top