【问题标题】:Sorting screen coordinates排序屏幕坐标
【发布时间】:2016-07-27 20:09:04
【问题描述】:

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

【问题讨论】:

  • 你说排序?使用std::sort
  • @CaptainObvlious 你打败了我。 en.cppreference.com/w/cpp/algorithm/sort
  • @CaptainObvlious 我将按哪个参数排序?
  • 全部。编写一个满足严格弱排序的比较器。另外,你有没有想过使用std::set
  • @LogicStuff 我想用set,但我认为你需要一个唯一的键为每个条目,文本不能是键,因为相同的文本可以在屏幕上打印多次.

标签: c++ sorting vector


【解决方案1】:

您需要一个满足严格弱排序的自定义比较器(函子、lambda 或重载的operator &lt;),您可以将其输入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,为您实现字典比较。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2023-03-29
    • 2018-01-29
    • 1970-01-01
    • 2017-12-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-12-19
    相关资源
    最近更新 更多