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.
- Sort the vector
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.
operator==for your struct.std::unique. But it didn't work.trueandfalseto initialise variables, and never elsewhere. Your test are terribly convoluted, you can just writereturn a.val < b.val;instead ofif (a.val < b.val) return true; else return false;, for instance. The whole first function should be written asreturn (a.key < b.key) or (a.key == b.key and a.val < b.val);Equivalently, the second would bereturn (a.key == b.key) and (a.val == b.val);