Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove Duplicate Entries in a C++ Vector

Just want to remove duplicates. Pool is vector<pair<string, int>> but I seem to miss some elements at the start of the vector somehow. Can anyone verify the logic of the removal? Thanks :)

Pool Master::eliminateDuplicates(Pool generation)
{
    for(int i = 0; i < generation.size(); i++)
    {
        string current = generation.at(i).first;

        for(int j = i; j < generation.size(); j++)
        {
            if(j == i)
            {
                continue;
            }
            else
            {
                string temp = generation.at(j).first;
                if(current.compare(temp) == 0)
                {
                    Pool::iterator iter = generation.begin() + j;
                    generation.erase(iter);
                }
            }
        }
    }

    return generation;
}
like image 595
Jarrod Cabalzar Avatar asked May 10 '13 06:05

Jarrod Cabalzar


People also ask

How do you remove duplicates from a vector vector?

A vector element is removed with the vector erase member function. The syntax is: constexpr iterator erase(const_iterator position); The argument is an iterator that points to the element, to be removed.

How do I remove duplicates from AC array?

We can remove duplicate element in an array by 2 ways: using temporary array or using separate index. To remove the duplicate element from array, the array must be in sorted order. If array is not sorted, you can sort it by calling Arrays. sort(arr) method.

What does vector Clear () do?

vector::clear() clear() function is used to remove all the elements of the vector container, thus making it size 0.


1 Answers

If you don't mind sorting the vector, then you can use std::unique. That would be O(Nlog(N))

#include <iostream>
#include <algorithm>
#include <vector>

int main() 
{
    std::vector<int> v{1,2,3,1,2,3,3,4,5,4,5,6,7};
    std::sort(v.begin(), v.end()); 
    auto last = std::unique(v.begin(), v.end());
    v.erase(last, v.end());
    for (const auto& i : v)
      std::cout << i << " ";
    std::cout << "\n";
}
like image 93
juanchopanza Avatar answered Nov 22 '22 10:11

juanchopanza