C ++:映射,键的上一项 [英] C++: Map, previous item of a key

查看:52
本文介绍了C ++:映射,键的上一项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有此地图: map< int,int>项目.给定一个键,我希望此映射返回与该键对应的项(如果存在),否则,该映射返回具有键的项立即小于给定键的项.例如,如果我有:

I have this map: map<int, int > items. Given a key, I want that this map returns the item corrisponding to the key if it present, otherwise the map returns the item with key immediately less than the given key. For example, if I have:

  items[0]=0;
  items[6]=10;
  items[15]=18;
  items[20]=22;

与key = 15相比,我希望地图返回值为18的项,否则对于key = 9,我希望地图返回值为10的项.

than for key=15, I want that the map returns item with value 18, otherwise for key=9, I want that map returns item with value 10.

我没有找到这种情况下的功能.但是我以这种方式尝试过:

I haven't find a function for this case. But I tried in this way:

itlow=items.lower_bound(key);
if(!items.count(key))
   itlow--;
return itlow->second;

这如我所愿,在地图中输入一个最小值 items [0] = 0 作为默认值,但我知道 itlow-; 不好编程.我能怎么做?谢谢大家

This works as I want, entering in the map a min value items[0]=0 for default, but I know that itlow--; it's not good programming. How can I do? thanks all.

推荐答案

您只需要检查您的 itlow 是否已经是 items.begin().如果是,则地图中没有这样的元素:

You just need to check if your itlow is already items.begin(). If it is, there's no such element in the map:

itlow=items.lower_bound(key);
if(itlow->first == key)
    return itlow->second;
else if(itlow != items.begin())
    itlow--;
    return itlow->second;
else
    throw some_exception();

代替抛出异常,您可以返回迭代器,然后如果找不到此类元素,则可以返回 items.end().

Instead of throwing exception, you may return iterator, and then you can return items.end() if no such element is found.

#include <iostream>
#include <map>

using namespace std;


map<int, int>::const_iterator find(const map<int, int> &items, int value)
{
    auto itlow = items.lower_bound(value);

    if(itlow->first == value)
        return itlow;
    else if(itlow != items.cbegin())
        return --itlow;
    else 
        return items.cend();

}

int main()
{
  map<int, int> items;
          items[2]=0;
  items[6]=10;
  items[15]=18;
  items[20]=22;

  auto i = find(items, 0);
  if(i != items.cend())
  {
     cout << i->second << endl;
  }
  i = find(items, 15);
  if(i != items.cend())
  {
    cout << i->second << endl;
  }
  i = find(items, 9);
  if(i != items.cend())
  {
    cout << i->second << endl;
  }
}

这篇关于C ++:映射,键的上一项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆