I need to implement an algorithm to eliminate duplicates from an array (without creating a new one). I watched the implementation of the function std :: unique in pros.
int* unique(int* first, int* last) { if (first == last) return last; int* result = first; while (++first != last) { if (*result != *first) { *(++result) = *first; } } return ++result; } Redid - removed templates. It seems that it even works, but I can not use it ... It is too inconvenient to use. I want to redo it into a normal version - at least with indices instead of this damn address arithmetic.
typedef struct Array { int* data; int length; } Array; Array array_distinct(Array arr) { int index = 0; for (int i = 1; i < arr.length - 1; i++) { if (arr.data[index] != arr.data[i]) { arr.data[++index] = arr.data[i]; } } arr.length = index; return arr; } int main() { int input[] = { 1, 1, 2, 4, 5, 5, 6 }; Array a; a.data = input; a.length = sizeof(input) / sizeof(int); Array b = array_distinct(a); for (int i = 0; i < b.length; i++) { printf("%d\n", b.data[i]); } return 0; } But something does not work out ... Help me please.