Pattu
Pattu

Reputation: 3809

C++ - Remove duplicates from a sorted vector of structs

I have a structure as shown below.

struct Num {
    uint64_t key;
    uint64_t val;
};

// Compare based on their key and value.
bool num_less(Num a, Num b)
{
    if(a.key < b.key)
        return true;
    else if(a.key == b.key)
    {
        if(a.val < b.val)
            return true;
        else
            return false;
    }
    else
        return false;
}

// Compare based on their key and value.
bool num_equal(Num a, Num b)
{
    return ((a.key == b.key) && (a.val == b.val)) ? true : false;
}

I have a vector of structs. I want to remove the duplicates from that vector. I tried the following approach.

  1. Sort the vector
  2. Remove the duplicates(consecutively placed)

    vector<Num> arr;

    sort(arr.begin(), arr.end(), num_less);

    arr.erase(std::unique(arr.begin(), arr.end(), num_less);, arr.end());

But when I run the above code, only the first element of the sorted vector is printed and rest of them are somehow deleted. I am not sure what am I doing wrong.

Edit - I tried with num_equal function in std::unique. And it worked.

Upvotes: 1

Views: 1191

Answers (1)

Bushuev
Bushuev

Reputation: 577

you need to define equal predicate

struct Num 
{
    unsigned int key;
    unsigned int val;
};

bool num_less(const Num &a, const Num &b)
{
    return (a.key<b.key)||(!(b.key < a.key))&&(a.val<b.val));
}
bool num_equal(const Num &a, const Num &b)
{
    return (a.key==b.key)&&(a.val==b.val);
}
int main()
{
    vector<Num> arr;
    Num temp;
    // add some examples
    temp.key=10; temp.val=20;
    arr.push_back(temp);        arr.push_back(temp);
    temp.key=11; temp.val=23;
    arr.push_back(temp);        arr.push_back(temp);
    temp.key=10; temp.val=20;
    arr.push_back(temp);        arr.push_back(temp);    arr.push_back(temp);
    //sort
    sort(arr.begin(),arr.end(),num_less);
    //delete dublicates
    arr.erase(unique(arr.begin(),arr.end(),num_equal),arr.end());
    return 0;
}

Upvotes: 2

Related Questions