Home > Blockchain >  Logic error in remove duplicates in a vector while preserving the order function
Logic error in remove duplicates in a vector while preserving the order function

Time:09-24

void vectorDeduplicator(std::vector<std::string>& inputVector){ 
     for(int i = 0; i < inputVector.size() - 1; i  ){
          for(int x = 1; x <= inputVector.size() - 1; x  )
                if(inputVector.at(i) == inputVector.at(x) && i != x){
                inputVector.erase(inputVector.begin()   x);    
          }
     }
}
Input: 1 1 2 2 4 4 3 3 1 1 3 3 3 2 2
Output: [1,2,4,1,3,2]

You can see the function I'm trying to use to remove duplicates inside of a vector. It works when duplicates are adjacent. I wouldn't like to use a faster and an efficient method without knowing anything about it that already exists within the standard library or anything else. I'd like to learn the algorithm behind it as this is for learning purposes.

CodePudding user response:

The problem is you ignore one value as you erase. You need to decrement x:

#include <vector>
#include <iostream>

void vectorDeduplicator(std::vector<int>& inputVector)
{ 
     for(int i = 0; i < inputVector.size() - 1; i  )
     {
          for(int x = 1; x < inputVector.size(); x  )
          {
                if(inputVector.at(i) == inputVector.at(x) && i != x)
                {
                    inputVector.erase(inputVector.begin()   x);
                    x--; // go one back because you erased one value
                }
          }

        // to debug
        for(const auto& x : inputVector)
            std::cout << x << " ";
        std::cout << std::endl;
     }
}

int main(){

    std::vector<int> vector{1, 1, 2, 2, 4, 4, 3, 3, 1, 1, 3, 3, 3, 2, 2};

    vectorDeduplicator(vector);

    // output
    for(const auto& x : vector)
        std::cout << x << " ";
    

    return 0;
}

The output then is:

1 2 2 4 4 3 3 3 3 3 2 2 
1 2 4 4 3 3 3 3 3 
1 2 4 3 3 3 3 3 
1 2 4 3 
1 2 4 3 
  • Related