In a programming task, I'm trying to ensure a particular vector contains only unique items. With primitive types, the operation is as simple as:
vector<int> lala;
lala.push_back(1);
lala.push_back(99);
lala.push_back(3);
lala.push_back(99);
sort(lala.begin(), lala.end()); // lala: 1, 3, 99, 99
lala.erase(unique(lala.begin(), lala.end()), lala.end()); // lala: 1, 3, 99
However, the problem is I'm not using int. But:
typedef struct
{
int x;
int y;
int maxX;
int maxY;
int width;
int height;
int id;
} Rect;
bool SameRect(Rect first, Rect second)
{
return first.x == second.x &&
first.y == second.y &&
first.width == second.width &&
first.height == second.height &&
first.maxX == second.maxX &&
first.maxY == second.maxY;
}
//...
vector<Rect> lala;
//...
sort(lala.begin(), lala.end());
lala.erase(unique(lala.begin(), lala.end(), SameRect), lala.end());
//...
Doesn't really work. What did I done wrong?
EDIT:
With sth's advice, I implemented two sorting predicate for std::sort():
bool SortRect(const Rect &first, const Rect &second)
{
if (first.x < second.x) return true;
if (first.x > second.x) return false;
if (first.y < second.y) return true;
if (first.y > second.y) return false;
if (first.maxX < second.maxX) return true;
if (first.maxX > second.maxX) return false;
if (first.maxY < second.maxY) return true;
if (first.maxY > second.maxY) return false;
if (first.width < second.width) return true;
if (first.width > second.width) return false;
if (first.height < second.height) return true;
if (first.height > second.height) return false;
if (first.id < second.id) return true;
if (first.id > second.id) return false;
return false;
}
But I found that it has the same effect as:
bool SortRect(const Rect &first, const Rect &second)
{
return first.x < second.x;
}
if SGI's documentation is anything to come by. The shorter, simple sorting predicate should work as well. My test has confirmed this (Although I have not try all possible combinations).