排序屏幕坐标

时间:2016-07-27 20:09:05

标签: c++ sorting vector

我有一个Vector 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;

1 个答案:

答案 0 :(得分:0)

您需要一个自定义比较器(仿函数,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,为您实现字典比对。