繁体   English   中英

如何使用不同类型的键搜索std :: map

[英]How can I search an std::map using a key of a different type

如果我有std::map<X, Blah> ,使用Y实例在地图中查找匹配项的最佳方法是什么?

假设Y的信息足以唯一地找到X ,但出于性能原因,我不想通过复制Y值来创建X的实例。

我意识到我可以通过为XY创建一个公共基类或接口并使其成为映射键来实现这一点,但还有其他方法吗? 例如,创建某种比较对象?

以下是示例代码:

class X
{
public:
    int id;
    int subId;
};

std::map<X, Details> detailsMap;

class Y
{
public:
    int getId();
    int getSubId();
    int someOtherUnrelatedThings1;
    int someOtherUnrelatedThings2;
};

现在,如果我有一个Y的实例,原则上我应该能够在我的地图中找到匹配的项目,因为我可以得到一个idsubId对。 但是,如果不创建X的实例并复制idsubId我可以这样做吗?

使用C ++ 14,您可以使用异构查找。

如果你想找到一个带有与std::map::find的参数相当的键的元素,你应该提供一个Comparator作为第三个模板参数,它应该将Comparator::is_transparent表示为一个类型。 它还应该包含bool operator()将你的map键与你想要的任何其他类型进行比较。

除了有趣的描述,这是一个例子:

struct X
{
    int id;
    int subid;
};

struct Details {};

struct Comparator
{
    using is_transparent = std::true_type;

    // standard comparison (between two instances of X)
    bool operator()(const X& lhs, const X& rhs) const { return lhs.id < rhs.id; }

    // comparison via id (compares X with integer)
    bool operator()(const X& lhs, int rhs) const { return lhs.id < rhs; }
    bool operator()(int lhs, const X& rhs) const { return lhs < rhs.id; }

    // Same thing with Y
    bool operator()(const X& lhs, const Y& rhs) const { return lhs.id < rhs.getId(); }
    bool operator()(const Y& lhs, const X& rhs) const { return lhs.getId() < rhs.id; }
};

int main()
{
    std::map<X, Details, Comparator> detailsMap = {
        { X{1, 2}, Details{} }, 
        { X{3, 4}, Details{} },
        { X{5, 6}, Details{} }
    };

    // it1 and it2 point to the same element.
    auto it1 = detailsMap.find(X{1, 2});
    auto it2 = detailsMap.find(1);

    std::cout << detailsMap.size() << std::endl;
    std::cout << std::boolalpha << (it1 == detailsMap.end()) << std::endl; // false
    std::cout << std::boolalpha << (it1 == it2) << std::endl; // true
}

但请注意,GCC在修订版219888之前没有实施。

C ++ 14为map排序添加了is_transparent支持。

struct compare_helper {
  X const* px = nullptr;
  Y const* py = nullptr;
  compare_helper(compare_helper&&)=default;
  compare_helper(X const& x):px(&x) {}
  compare_helper(Y const& y):py(&y) {}
  explicit operator bool()const{return px&&py;}
  friend bool operator<(compare_helper&& lhs, compare_helper&& rhs) {
    if (!lhs || !rhs) {
      return !rhs < !lhs;
    }
    // TODO: compare lhs and rhs based off px and py
  }
};
struct ordering_helper {
  using is_transparent=std::true_type;
  bool operator()(compare_helper lhs, compare_helper rhs)const{
    return std::move(lhs)<std::move(rhs);
  }
};

现在重新定义你的std::map

std::map<X, Details, ordering_helper> detailsMap;

你完成了 您现在可以将Y const&传递给detailsMap.find或其他任何东西。

现在// TODO: compare lhs and rhs based off px and py有点烦人。

但它应该是可写的。

如果你需要许多不同的类来与X进行比较,你需要一个大的compare_helper类来保存每一个,或者你需要以某种方式键入 - 擦除操作。

基本上, compare_helper需要存储指向X的指针,或者std::function< int(X const&) > ,它告诉您X是否小于,等于或大于其他参数。 (你会注意到在将YYZY进行比较时失败 - 在这种情况下,返回false应该是安全的,因为在给定的地图搜索中你只会看到一个非X )。

我们可以将这与compare_helper的定义与一些ADL分离:

struct compare_helper {
  X const* px = nullptr;
  using f_helper = std::function< int(X const&) >;
  f_helper not_X;
  compare_helper(compare_helper&&)=default;
  compare_helper(X const& x):px(std::addressof(x)) {}
  template<class NotX,
    class=std::enable_if_t< std::is_convertible<
      decltype(compare_with_X( std::forward<NotX>(notx) ))
      , f_helper
    >{}
  >
  compare_helper( NotX&& notx ):
    not_X( compare_with_X( std::forward<NotX>(notx) ) )
  {}
  explicit operator bool()const{return px&&not_X;}
  friend bool operator<(compare_helper&& lhs, compare_helper&& rhs) {
    if (!lhs || !rhs) {
      return !rhs < !lhs;
    }
    if (lhs.px && rhs.px) { return *lhs.px < *rhs.px; }
    if (lhs.px && rhs.not_X) { return rhs.not_X(*lhs.px) < 0; }
    if (lhs.not_X && rhs.px) { return lhs.not_X(*rhs.px) > 0; }
    else return false;
  }
};

现在,最终用户只需要覆盖要与X比较的类型的命名空间中的自由函数compare_with_X ,以返回std::function<int(X const&)> ,上面的映射允许从非您查找X型。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM