Removing things that occur once only from an array

I wonder if there is a better way…

#include <iostream>
#include <string>
#include <vector>
#include <map>

using namespace std;


void remonce(vector<int> &array) {

  map<int,int> counts;

  for(size_t n=0;n<array.size();n++) {
    counts[array[n]]++;
  }

  vector<int> newarray;
  for(size_t n=0;n<array.size();n++) {
    if(counts[array[n]] != 1) {
      newarray.push_back(array[n]);
    }
  }

  array = newarray;
}

int main() {

  vector<int> array;
  array.push_back(4);
  array.push_back(4);
  array.push_back(3);
  array.push_back(3);
  array.push_back(8);
  array.push_back(16);
  array.push_back(8);

  remonce(array);

  for(size_t n=0;n<array.size();n++) {
    cout << array[n] << endl;
  }
}

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>