从有序容器中制作比较器 [英] Making a comparator from an ordered container

查看:57
本文介绍了从有序容器中制作比较器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出对象列表,最简单的方法来创建函子对象以充当比较器,以使比较器遵守列表中对象的顺序。确保列表中的对象是唯一的,并且列表包含所有可能对象的空间。

Given a list of objects, what is the cleanest way to create a functor object to act as a comparator, such that the comparator respects the ordering of the objects in the list. It is guaranteed that the objects in the list are unique, and the list contains the entire space of possible objects.

例如,假设我们有:

const std::vector<std::string> ordering {"dog", "cat", "mouse", "elephant"};

现在,我们希望函数充当比较器,比如说映射:

Now we want a function to act as a comparator, say for a map:

using Comparator = std::function<bool(const std::string&, const std::string&>;
using MyMap      = std::map<std::string, int, Comparator>;

我有解决方案,但这不是我所说的那么漂亮:

I have a solution, but it's not what I'd call pretty:

const auto cmp = [&ordering] (const auto& lhs, const auto& rhs)
                 {
                     const std::array<std::reference_wrapper<const std::decay_t<decltype(lhs)>, 2> values {lhs, rhs};
                     return *std::find_first_of(std::cbegin(ordering), std::cend(ordering),
                                                std::cbegin(values), std::cend(values),
                                                [] (const auto& lhs, const auto& rhs) {
                                                    return lhs == rhs.get();
                                                }) == lhs;
                 };

是否有些不那么冗长?

推荐答案

您可以使用:

const std::vector<std::string> ordering {"dog", "cat", "mouse", "elephant"};

struct cmp
{
   bool operator()(const std::string& lhs, const std::string& rhs)
   {
      return (std::find(ordering.begin(), ordering.end(), lhs) <
              std::find(ordering.begin(), ordering.end(), rhs));
   }
};

using MyMap = std::map<std::string, int, cmp>;

请参见 http://ideone.com/JzTNwt

这篇关于从有序容器中制作比较器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆