【问题标题】:What is the most efficient std algorithm to find the closest range of an input number in a std::map?在 std::map 中找到输入数字的最接近范围的最有效的 std 算法是什么?
【发布时间】:2016-08-16 07:52:53
【问题描述】:

我的数据将存储在整数和整数的映射中 关键是任意数字的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]。 但是,输出值(即iterator->second)的范围检查逻辑应单独进行,以验证它是否在正确的范围内。

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

【问题讨论】:

    标签: c++ algorithm stdmap


    【解决方案1】:

    您有std::lower_bound 来查找不符合您搜索值的最低项目。

    auto it = mymap.lower_bound( value );
    

    来自cplusplus map::lower_bound

    一个类似的成员函数,upper_bound,具有与 lower_bound 相同的行为,除了 map 包含一个 key 等效于 k 的元素:在这种情况下,lower_bound 返回一个指向该元素的迭代器,而 upper_bound 返回指向下一个元素的迭代器。

    所以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 --;
    }
    

    【讨论】:

      【解决方案2】:

      upper_bound 查找键大于 (>) 提供的键或在地图末尾停止。

      lower_bound 查找键大于或等于 (>=) 提供的键或在地图末尾停止 p>

      下面是查找输入数字的最接近范围的代码:Demo

      typedef std::map<int,int>::iterator Iter;
      
      Iter getIterator(std::map<int,int> &m, int val) {
          Iter lb = m.upper_bound(val);
          if(lb == m.begin()) {
              return m.end();
          }
          Iter it = std::prev(lb);
          if(it->first <= val && val <= it->second ) {
              return it;
          }
          else{
              return m.end();
          }
      }
      int main() {
          // your code goes here
          std::map<int,int> mymap;
          mymap[100]=200;
          mymap[1000]=2000;
          mymap[2000]=2500;
          mymap[3000]=4000;
          mymap[5000]=5100;
      
          int a[4]{4500, 4000, 150, 0};
          for(int x : a){
              Iter it = getIterator(mymap, x);
              if(it != mymap.end()){
                  cout << "Value " << x << " : Found in range: " << it->first << ", " << it->second <<endl;
              }else{
                  cout << "Value " << x << " : NOT FOUND!" <<endl;
              }
          }
          return 0;
      }
      

      【讨论】:

        猜你喜欢
        • 2019-06-30
        • 1970-01-01
        • 2019-01-19
        • 1970-01-01
        • 2021-07-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多