【问题标题】:why std::max_element over std::map within some lower_bound not working?为什么 std::max_element 在某些 lower_bound 内的 std::map 不起作用?
【发布时间】:2015-03-17 04:27:34
【问题描述】:

我不确定为什么以下 sn-p 不起作用: lower_bound 调用返回键 7,这是预期的。然后begin()lower_bound() 之间的std::max_element 迭代器应该返回6,因为它应该在键4 和键7 之间搜索,并且键7 的最大值是6。 但由于某种我无法弄清楚的原因,它返回了最后一个 pair(15, 12)

bool cmp(const std::pair<T, T>& p1, const std::pair<T, T>& p2) 
{
    return p1.second < p2.second;
}

int main()
{
    std::map< T, T, std::greater<T> > store;
    std::map< T, T, std::greater<T> >::iterator found_max, lower;

    store[ 4 ] = 2;
    store[ 7 ] = 6;
    store[ 10 ] = 2;
    store[ 15 ] = 12;
    lower = store.lower_bound( 8 );

    printf("%ld %ld\n", lower->first,lower->second);

    found_max = std::max_element(store.begin(), lower, cmp);
    printf("%ld %ld\n", found_max->first,found_max->second);

    return 0;
}

【问题讨论】:

  • map 的默认排序(使用std::less&lt;T&gt;)从最小到最大排序项目。指定std::greater&lt;T&gt; 意味着它们将从大到小排序。

标签: c++ stl stdmap


【解决方案1】:
std::map< T, T, std::greater<T> > store;

store 的键按降序 顺序排序。因此,[store.begin(), lower) 包含 (15, 22)(10, 2)。最大值为(15, 22)的元素。

【讨论】:

  • 没错,下面的调用应该给我正确的结果。 found_max = std::max_element(lower, store.end(), cmp)
猜你喜欢
  • 2012-02-05
  • 1970-01-01
  • 2014-10-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-01-17
  • 1970-01-01
相关资源
最近更新 更多