Home > OS >  How to remove duplicates elements in nested list in c
How to remove duplicates elements in nested list in c

Time:12-10

I'm trying to solve one np-complete problem in C . I can solve this problem in Python but running time is relatively slow, so that's why I switch to C . In one part of the problem I need to clean duplicate elements from my list.

I have a list the type is list<list<int> > in c . My list contains duplicate elements for example:

If I send list below as an input:

[ [1,2,3] , [2,3,4] , [2,3,4] , [4,5,6] ]

I should get [ [1,2,3] , [2,3,4] , [4,5,6] ] as a result from the method.

So, how can I make my nested list contains only unique elements? Are there any efficient way or built-int function in c instead of using nested loop?

CodePudding user response:

std::unique works just fine: (where input is your nested list)

auto it = std::unique(begin(input), end(input));
input.erase(it, end(input));

CodePudding user response:

I know this solution is not rational, but I offer to use set<list<int>>:

#include <iostream>
#include <list>
#include <set>
using namespace std;
template<class Type>
void showContentContainer(Type& input)
{
    for(auto itemSet : input)
    {
        for(auto iteratorList=itemSet.begin(); iteratorList!=itemSet.end();   iteratorList)
        {
            cout<<*iteratorList<<", ";
        }
        cout<<endl;
    }
    return;
}
void solve()
{
    list<list<int>> listOfLists={{1, 2, 3}, {2, 3, 4}, {2, 3, 4}, {4, 5, 6}};
    set<list<int>> setOfLists;
    for(auto iterator=listOfLists.begin(); iterator!=listOfLists.end();   iterator)
    {
        setOfLists.insert(*iterator);
    }
    cout<<"Before, listOfLists <- "<<endl;
    showContentContainer(listOfLists);
    listOfLists.clear();
    for(auto item : setOfLists)
    {
        listOfLists.push_back(item);
    }
    cout<<endl<<"After, listOfLists <- "<<endl;
    showContentContainer(listOfLists);
    cout<<endl;
    return;
}
int main()
{
    solve();
    return 0;
}

Here is the result:

Before, listOfLists <- 
1, 2, 3, 
2, 3, 4, 
2, 3, 4, 
4, 5, 6, 

After, listOfLists <- 
1, 2, 3, 
2, 3, 4, 
4, 5, 6, 
  • Related