排序屏幕坐标

Sorting screen coordinates

本文关键字:屏幕坐标 排序      更新时间:2023-10-16

我有一个向量textCommands,它包含一个名为TextCommand的结构,包含一个RECT和一个字符串;并且RECT的值topleftbottomright都在屏幕坐标中。我想知道如何对这个向量进行排序,这样我就可以调用std::unique并删除重复的条目。重复条目是具有相同字符串和相同RECT的条目,其中所有值都相同。

//Location in screen coordinates(pixels)
struct RECT
{
    int top;
    int left;
    int bottom;
    int right;
};
//text at location RECT
struct TextCommand
{
    std::string text;
    RECT pos;
};
std::vector<TextCommand> textCommands;

您需要一个满足严格弱排序的自定义比较器(函子、lambda或重载operator <),可以将其输入到std::sortstd::set中。最简单的是:

#include <tuple>
struct TextCommandCompare
{
    bool operator()(TextCommand const& a, TextCommand const& b) const
    {
        return std::tie(a.text, a.pos.top, a.pos.left, a.pos.bottom, a.pos.right) <
            std::tie(b.text, b.pos.top, b.pos.left, b.pos.bottom, b.pos.right);
    }
};

std::tie创建一个std::tuple,为您实现字典比较。