Michael,

Why not just use a std::set<int> here?  Repeated inserts of the same
value will be ignored.

True, but that will use extra memory. Since pointers are iterators,
this can be done on ordinary array in place without extra memory. Only
thing is that unique() function modifies the original array. I have
used back_insert_iterator with extra class to keep track of the number
of unique elements, but now the code is not neat anymore:


#include <vector>
#include <algorithm>
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;

struct Count {
 int num;
 Count() : num() {}
 void push_back(int n) {++num;}
 typedef int& const_reference;
};

int main()
{
 srand(time(NULL));
 enum {SIZE=100};
 int array[SIZE];
 for (int i=0; i < SIZE; ++i)  // populate with random ints
   array[i] = rand()%70;
 sort(array,array+SIZE);
 Count count;
 unique_copy(array, array+SIZE, back_insert_iterator<Count>(count));
 cout <<"Unique size: " <<count.num <<endl;
 return 0;
}


--
To UNSUBSCRIBE, email to [EMAIL PROTECTED] with a subject of "unsubscribe". Trouble? Contact [EMAIL PROTECTED]

Reply via email to