在具有结构的STL向量上使用唯一的

Hao*_*Lim 2 c++ stl vector unique

在编程任务中,我试图确保特定向量仅包含唯一项.对于原始类型,操作非常简单:

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
Run Code Online (Sandbox Code Playgroud)

但是,问题是我没有使用int.但:

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());
//...
Run Code Online (Sandbox Code Playgroud)

不起作用.我做错了什么?

编辑:

根据sth的建议,我为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;
}
Run Code Online (Sandbox Code Playgroud)

但我发现它具有与以下相同的效果:

bool SortRect(const Rect &first, const Rect &second)
{
    return first.x < second.x;
}
Run Code Online (Sandbox Code Playgroud)

如果SGI的文件是什么来的话.较短,简单的排序谓词也应该起作用.我的测试证实了这一点(虽然我没有尝试所有可能的组合).

sth*_*sth 5

您还必须定义一个比较函数,用于sort()对Rects进行排序.此比较函数应实现严格的弱排序,以便相等的元素在向量中彼此相邻.

如果向量未排序,unique()则不会找到未排序的重复元素.