【问题标题】:How to sort std :: MAP for the second parameter when the two template parameters?两个模板参数时如何为第二个参数排序std :: MAP?
【发布时间】:2015-01-16 11:21:34
【问题描述】:

怎么办?找了很多例子,但是找不到带参数模板的例子。我不知何故没有工作比较器。

std::map<K, CacheEntry<T>*, Comparator<K, CacheEntry<T>>> timeMap_;

template<typename T1, typename T2>
        struct Comparator
        {
            typedef std::pair<T1, T2> type;
            bool operator()(const type& l, const type& r) const
            {
                auto nowTime = std::chrono::system_clock::now();
                auto timeL = nowTime - l.second->creationTime();
                auto timeR = nowTime - r.second->creationTime();
                return (std::chrono::duration_cast<std::chrono::microseconds>(timeL).count() > std::chrono::duration_cast<std::chrono::microseconds>(timeR).count());
            }
        };

错误:

错误 1 ​​错误 C2664: 'bool diadoc::cache::比较器 *>::operator ()(const std::pair &,const std::pair &) const' : 无法将参数 1 从 'const std::wstring' 转换为 'const std::pair &' c:\program files (x86)\microsoft visual studio 12.0\vc\include\xutility 521 1 DiadocClient

我尝试使用:

template<typename T1, class T2>

但它太不工作了。 按第二个参数ma​​p排序。

【问题讨论】:

  • 您的示例中的K 是什么?无论如何,传递给std::map 的比较器对象必须接受两个K 类型的对象作为参数。你不能把模板参数切换到map吗?
  • @Angew K - 是关键,但我不想按键排序。我需要对字段 creationTime_ 类 CacheEntry 进行排序。也就是说,我要对第二个字段进行排序。
  • 这没有意义。 std::map 按关键字排序,并利用其内容已排序这一事实来提供对数时间唯一性检查和访问。您能否清楚地说明您的要求:您的唯一性标准、排序标准、访问/修改时间复杂度标准是什么?你可能需要一个更复杂的容器,比如boost::multi_index
  • 有一个唯一的key,我们找到一个存储时间和值的对象。底线是,当我想删除最旧的成员时,我呼吁他 map.begin()。这个容器不适合我吗?
  • 请尽量把要求表述得更清楚一些,并将它们添加到问题中;它将大大改善它(实际上是让它自己负责)。

标签: c++11 dictionary compare


【解决方案1】:

从您的 cmets 看来,您需要一个容器来:

  • 存储包含KCacheEntry&lt;T&gt;的对象
  • 不允许两个对象具有相同的K
  • 根据CacheEntry&lt;T&gt;对对象进行排序

没有直接支持这一点的标准容器。你可以使用boost::multi_index_container,像这样:

typedef std::pair<K, CacheEntry<T>*> DataItem;


MyTimeType getTime(const DataItem &item)
{
  return getTimeSomehowFrom(item);
}


typedef multi_index_container<
  DataItem,
  indexed_by<
    ordered_non_unique<global_fun<DataItem, MyTimeType, &getTime>>,
    hashed_unique<member<DataItem, K, &DataItem::first>>
  >
> MyContainer;

(为简洁起见,代码假定所有相关的#includes 和using namespace 指令)。

上面的代码不是复制&粘贴&使用的形式,但它应该是一个让你开始的指针。您可以阅读多索引容器并根据上述想法构建以满足您的需求(例如为索引添加标签)。

索引的顺序(有序,然后是唯一的)很重要——为了方便,容器本身继承了第一个索引的接口。在上述情况下,这将允许您将其视为由getTime() 的结果排序的DataItems 的集合,同时不允许K 的重复值。


作为旁注,请注意您不需要将now() 拖到比较器中。如果是(now - t1) &lt; (now - t2),那么只需t2 &gt; t1

【讨论】:

    【解决方案2】:

    不确定您要做什么,但 std::map 仅比较键(即示例代码中的 K 类型)。

    您定义了一个比较一对的比较器,这不是std::map 需要的,因此出现了错误。

    如果您的地图可能包含多个具有相同键的条目,则应改用multimap

    【讨论】:

    • 键 - 在我的 std::map 中是唯一的。我需要一个按第二个字段排序的地图,即 CacheEntry.creationTime_。这不可能?
    猜你喜欢
    • 1970-01-01
    • 2016-04-24
    • 1970-01-01
    • 2016-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-05-03
    相关资源
    最近更新 更多