簡體   English   中英

在std :: map中找到最接近輸入數范圍的最有效的std算法是什么?

[英]What is the most efficient std algorithm to find the closest range of an input number in a std::map?

我的數據將存儲在整數和整數的映射中。鍵是任何數字的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

類似的成員函數upper_bound與lower_bound具有相同的行為,除非地圖包含具有等於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 --;
}

upper_bound查找大於> )提供的鍵的鍵,或者在地圖末尾停止。

lower_bound查找大於或等於> = )提供的鍵的鍵,或者在地圖末尾停止

下面給出了找到最接近輸入數范圍的代碼: 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;
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM