Eliminating repeated values from a vector

Asked

Viewed 490 times

2

Hello, folks briefly my problem is to eliminate repeated values of an array, here is my code and just below a brief explanation.

=========================================================================

#include <iostream>
#include <iterator>

using namespace std;

int* unique( int *first, int *last);
int main(){

int A[] = { 1, 2, 1, 2, 3, 3, 1, 2, 4, 5, 3, 4, 5 };

//aplicar unique sobre A.

auto last = unique(std::begin(A), std::end(A));

//o comando abaixo deveria imprimir A com o conteudo 1, 2, 3, 4, 5.
for( auto i = std::begin(A); i != last; ++i){
    std::cout << *i << " ";
}

std::cout << endl;

//mostrar o novo tamanho de A, que seria 5.
std:: cout << ">>O comprimento logico de A apos o unique() eh: " << std::distance(std::begin(A), last) << std::endl;
std::cout << ">>O retorno indica a posição do elemento: " <<*last << std::endl;


    return 0;
}


int* unique( int *first, int *last){
auto slow = first+2;
    for (auto fast = first+2; fast != last; ++fast){
        for (auto i = slow; i != first; /*empty*/){
            if(*fast != *i ){
                swap(*slow++, *fast);
            }
            --i;
        }
    }
    return slow;
}

=========================================================================

Well, basically I send two pointers indicating the beginning and the end of my vector, then create two more pointers (slow and fast), the fast runs through the vector and tests if the current element is different than the one behind the slow, causing it to push the repeated values to the end of the vector and leaving only the unique values at the beginning, the function returns slow, that is, it indicates where the unique values end, the problem arises exactly in this part of slow-to-back testing, the function is not returning me the exact value, wanted to make this test using the swap function().

  • Put the code in text to make it easier for us. And say the final goal, because it is possible that another algorithm is better than this.

  • thanks for the tip.

  • Why do you skip 2 at the beginning?

No answers

Browser other questions tagged

You are not signed in. Login or sign up in order to post.