How to remove duplicates from an array of integers in C++?

The following piece of code traverses the list of integers, removes duplicate numbers, if any, and returns the remaining list.

More like this:

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

void removeDuplicates(std::vector<int> &list)
{
    auto end = list.end();
    for (auto i = list.begin(); i != end; ++i)
    {
        end = std::remove(i + 1, end, *i);
    }
    list.erase(end, list.end());
}

int main()
{
    std::vector<int> v = { 7, 2, 3, 5, 1, 7, 4, 7, 8, 1 };
    removeDuplicates(v);
    for (auto i = v.cbegin(); i != v.cend(); ++i)
        std::cout << *i << ' ';
    return 0;
}

 

Output:

 

Leave a Reply

Your email address will not be published.