How do I remove duplicates from a set?

I know that C ++ sets do not allow duplication, however what I am trying to achieve is slightly different. My program reads a data file in the form below, imports the data and does some calculations with it.

If I take the number of counts of a set through set1.size()

, it will count pairs like 3 9

and 3 9

, times, since it does not accept duplicates. However, I also want something like 3 9

and 9 3

count as one.

1    4
5    8
3    9
3    9
9    3
3    0
... so on

      

So in the above data (only 6 lines), if I did set1.size()

, I want to say 4. (3,9)(3,9)&(9,3)

should only be counted once. My code is below, this is how I insert data into a set and then I COUT the size later.

string in;
set<pair<int, int> > set1;
while (getline(fs, in)) {
    istringstream iss(in);
    int j, k;   
    if (iss >> j >> k) {
        set1.insert({j, k});                                    
    } 
}
}

      

+3


source to share


2 answers


I think even this would work:



if( iss >> j >> k){
   if(j > k) set1.insert({j,k});
   else set1.insert({k,j});
}

      

+2


source


You can add your own comparison function to the set. Then you can handle two different pairs the same way.

Something like that:

class MyCompare
{
public:

    bool operator () (const pair<int, int> &left, const pair<int, int> &right)
    {
        pair<int, int> orderedLeft = left;
        if (orderedLeft.first > orderedLeft.second)
            swap(orderedLeft.first, orderedLeft.second);

        pair<int, int> orderedRight = right;
        if (orderedRight.first > orderedRight.second)
            swap(orderedRight.first, orderedRight.second);

        return orderedLeft < orderedRight;
    }
};

      



Then declare your collection using this:

set<pair<int, int>, MyCompare > set1;

      

Obviously the code needs to be cleaned up a bit (remove duplication, etc.).

+2


source







All Articles