Search code examples
c++arrayselementunique

How to efficiently extract unique values from array?


I would like to extract unique values from my (dynamically allocated) array. I have something like this :

    [0]     0   int
    [1]     1   int
    [2]     2   int
    [3]     2   int
    [4]     2   int
    [5]     5   int
    [6]     6   int
    [7]     6   int
    [8]     8   int
    [9]     9   int
    [10]    10  int
    [11]    8   int
    [12]    12  int
    [13]    10  int
    [14]    14  int
    [15]    6   int
    [16]    2   int
    [17]    17  int
    [18]    10  int
    [19]    5   int
    [20]    5   int

I would like to have array of size 12 with every record in it being unique value form the other array.

How can I do that ?

EDIT I forgot to mention that I cannot use STL containers (like std::vector or std::list)


Solution

  • First you need to sort the array, then iterate over the sorted array and check if the previous or next entry are the same as the current entry. If not then the value is unique.

    Edit: I might have misunderstood the question... One way to get what you want is to iterate over the array. For each value check the value already exists in the other array, if not the copy it there. This might have to be done in two steps, once to get the number of unique entries (using an array of the same size as the existing) and one to get an array of correct size.