【问题标题】:interval map in C++C++ 中的区间映射
【发布时间】:2013-08-10 07:49:06
【问题描述】:

我需要将一些区间(实际上是地址区间)映射到对象 ID。

我尝试使用boost的interval_map,这个例子看起来很漂亮,它很容易枚举所有的区间,比如:

while(it != party.end())
{
    interval<ptime>::type when = it->first;
    // Who is at the party within the time interval 'when' ?
    GuestSetT who = (*it++).second;
    cout << when << ": " << who << endl;
}

哪些输出:

----- 派对嘉宾的历史 ------------- [2008-May-20 19:30:00, 2008-May-20 20:10:00): Harry Mary [2008-5-20 20:10:00,2008-5-20 22:15:00):戴安娜·哈里·玛丽·苏珊 [2008-May-20 22:15:00, 2008-May-20 23:00:00):戴安娜·哈里·玛丽·彼得·苏珊 [2008-May-20 23:00:00,2008-May-21 00:00:00):戴安娜·彼得·苏珊 [2008 年 5 月 21 日 00:00:00,2008 年 5 月 21 日 00:30:00):彼得

但它不能做这样的事情:

interval<ptime>::type when = 
    interval<ptime>::closed(
        time_from_string("2008-05-20 22:00"),
        time_from_string("2008-05-20 22:01"));

    GuestSetT who = party[when];

    cout << when << ": " << who << endl;

它输出:错误:'party[when]'中的'operator[]'不匹配 看起来很奇怪,因为map的主要功能在operator[]

所以我无法获得“在给定时间参加聚会的人”的信息

这个问题有现成的解决方案吗?

【问题讨论】:

  • 非常感谢,Cv_and_he!您的两种解决方案都有效。
  • 正确答案由stackexchange的用户cv_and_he给出:interval&lt;ptime&gt;::type when = interval&lt;ptime&gt;::closed( time_from_string("2008-05-20 22:00"), time_from_string("2008-05-20 22:01")); interval_map&lt;ptime, GuestSetT&gt;::const_iterator iter = party.find(when); cout &lt;&lt; iter-&gt;first &lt;&lt; ": " &lt;&lt; iter-&gt;second &lt;&lt; std::endl;
  • 第二个他(cv_and_he's)的正确解决方案是:GuestSetT who2 = party(time_from_string("2008-05-20 22:00")); cout &lt;&lt; "2008-05-20 22:00 : " &lt;&lt; who2 &lt;&lt; endl;
  • 我不确定它是否正确/您想要什么。你可以把它作为一个答案(也许包括上下文的其余代码),我会赞成它。

标签: boost map interval-tree


【解决方案1】:

这有点违反直觉,但 () 运算符正是您要找的。从文档中,operator() 被定义为“返回 [ing] 键 x 的映射值。该运算符仅适用于总映射。”

来源:http://www.boost.org/doc/libs/1_54_0/libs/icl/doc/html/boost_icl/function_reference/selection.html

【讨论】:

    猜你喜欢
    • 2012-10-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-04-08
    相关资源
    最近更新 更多