编程语言
首页 > 编程语言> > c – 在std :: map中找到最接近输入数范围的最有效的std算法是什么?

c – 在std :: map中找到最接近输入数范围的最有效的std算法是什么?

作者:互联网

我的数据将存储在整数和整数的映射中
关键是任何数字的start_range
值为end_range

例如我的地图将如下所示:

  std::map<int,int> mymap;
  mymap[100]=200;
  mymap[1000]=2000;
  mymap[2000]=2500;
  mymap[3000]=4000;
  mymap[5000]=5100;

现在,如果我的输入数字是150,那么算法应该将一个迭代器返回到mymap [100].
但是,具有输出值(即迭代器 – >秒)的范围检查逻辑应单独完成,以验证它是否落在正确的范围内.

对于输入数字4500,它可能返回mymap [5000],但范围检查逻辑应该失败,因为它是从5000到5100.
请注意,地图中没有OVERLAP范围.

解决方法:

你有std :: lower_bound来找到不符合你的搜索值的最低项目.

auto it = mymap.lower_bound( value );

cplusplus map::lower_bound

A similar member function, upper_bound, has the same behavior as lower_bound, except in the case that the map contains an element with a key equivalent to k: In this case, lower_bound returns an iterator pointing to that element, whereas upper_bound returns an iterator pointing to the next element.

因此lower_bound返回不小于搜索的第一个值.这意味着对于前面的值,您需要lower_bound – 1,但仅限于lower_bound!= begin()的情况

auto it = mymap.lower_bound( value );
if( it->first != value && it != mymap.begin() ) {
    it --;
}

或者使用upper_bound

auto it = mymap.upper_bound( value );
if( it != mymap.begin() ) {
    it --;
}

标签:c,algorithm,stdmap
来源: https://codeday.me/bug/20190824/1703481.html