如何使用 std::map 的比较模板参数进行值比较? [英] How to use the Compare template parameter of std::map for value comparison?

查看:39
本文介绍了如何使用 std::map 的比较模板参数进行值比较?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用此代码:

namespace nonstd {模板 <class Key,T级,类比较 = std::greater,class Allocator = std::allocator>>使用 map = std::map;}int main() {nonstd::map常量值 = {{'A', 3}, {'B', 2}, {'C', 5}};for (auto const& value : values) {std::clog <<价值.第一<<": "<<value.second<

我希望:

C : 5答:3乙:2

但我得到了:

C : 5B : 2//<---答:3

我检查了 std::map 的 GNU 实现,我看到了我们传递的 Compare 模板参数,将用作 Key 的比较函数:

但它也有两个返回比较对象的函数:

有没有办法使用Compare模板参数进行值比较?

解决方案

有没有办法使用比较模板参数进行值比较?

不,没有.std::map 的元素仅根据键进行排序.

如果你想要一个 std::pair<char,size_t> 的容器按照 size_t 排序,你可以使用 std::set<std::pair<char,size_t>> 带有仅比较 second 成员的自定义比较器.尽管这与您的地图非常不同,因为该集合仅存储具有唯一 second 的元素(由于自定义比较器),而地图存储具有唯一键的元素.

如果没有其他帮助,您始终可以使用 std::vector<std::pair<char,size_t>> 并使用 std::sort 对其进行排序,并使用 std::find_if 在插入时检查唯一性.

With this code:

namespace nonstd {
template <class Key,
          class T,
          class Compare = std::greater<T>,
          class Allocator = std::allocator<std::pair<Key const, T>>
          >
using map = std::map<Key, T, Compare, Allocator>;
}

int main() {
  nonstd::map<char, std::size_t> const values = {
    {'A', 3}, {'B', 2}, {'C', 5}
  };

  for (auto const& value : values) {
    std::clog << value.first << " : " << value.second << std::endl;
  }
}

I expect:

C : 5
A : 3
B : 2

But instead I got:

C : 5
B : 2 // <---
A : 3

I checked the GNU implementation of std::map and I saw the Compare template parameter we pass, will be used as a compare function for the Key:

But it also has two functions that return the comparison object:

Is there any way to use the Compare template parameter for value comparison?

解决方案

Is there any way to use the Compare template parameter for value comparison?

No there isnt. A std::maps elements are sorted with respect to the keys only.

If you want a container of std::pair<char,size_t> sorted with respect to the size_ts you could use a std::set< std::pair<char,size_t>> with a custom comparator that only compares the second member. Though this will be very different from your map, because the set would only store elements with unique second (due to the custom comparator), while the map stores elements with unique keys.

If nothing else helps you can always use a std::vector< std::pair<char,size_t>> and sort it with std::sort and use std::find_if to check for uniqueness upon insertion.

这篇关于如何使用 std::map 的比较模板参数进行值比较?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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