2014-11-01 20 views

回答

3

請嘗試以下

auto minmax = std::minmax(KEY_1, KEY_2, m.key_comp()); 

auto first = m.lower_bound(minmax.first); 
auto last = m.upper_bound(minmax.second); 

下面是一個示範項目:

#include <iostream> 
#include <map> 
#include <algorithm> 

int main() 
{ 
    std::map<int, int> m = 
    { 
     { 1, 10 }, { 2, 20 }, { 3, 30 }, {4, 40 }, { 5, 50 }, { 6, 60 }, { 7, 70 } 
    }; 

    int key1 = 5; 
    int key2 = 3; 

    auto minmax = std::minmax(key1, key2, m.key_comp()); 

    auto first = m.lower_bound(minmax.first); 
    auto last = m.upper_bound(minmax.second); 

    for (auto current = first; current != last; ++current) 
    { 
     std::cout << "{ " << current->first 
        << ", " << current->second 
        << " }" << std::endl; 
    } 

    return 0; 
} 

輸出是

{ 3, 30 } 
{ 4, 40 } 
{ 5, 50 } 

或者一個更有趣的例子

#include <iostream> 
#include <map> 
#include <algorithm> 
#include <functional> 

int main() 
{ 
    std::map<int, int> m1 = 
    { 
     { 1, 10 }, { 2, 20 }, { 3, 30 }, { 4, 40 }, { 5, 50 }, { 6, 60 }, { 7, 70 } 
    }; 

    int key1 = 5; 
    int key2 = 3; 

    auto minmax1 = std::minmax(key1, key2, m1.key_comp()); 

    auto first1 = m1.lower_bound(minmax1.first); 
    auto last1 = m1.upper_bound(minmax1.second); 

    for (auto current = first1; current != last1; ++current) 
    { 
     std::cout << "{ " << current->first 
        << ", " << current->second 
        << " }" << std::endl; 
    } 

    std::cout << std::endl; 

    std::map<int, int, std::greater<int>> m2 = 
    { 
     { 1, 10 }, { 2, 20 }, { 3, 30 }, { 4, 40 }, { 5, 50 }, { 6, 60 }, { 7, 70 } 
    }; 

    auto minmax2 = std::minmax(key1, key2, m2.key_comp()); 

    auto first2 = m2.lower_bound(minmax2.first); 
    auto last2 = m2.upper_bound(minmax2.second); 

    for (auto current = first2; current != last2; ++current) 
    { 
     std::cout << "{ " << current->first 
        << ", " << current->second 
        << " }" << std::endl; 
    } 

    return 0; 
} 

輸出是

{ 3, 30 } 
{ 4, 40 } 
{ 5, 50 } 

{ 5, 50 } 
{ 4, 40 } 
{ 3, 30 } 

如果你想排除的範圍的上限,那麼你必須方法upper_bound的號召代替以lower_bound這是該代碼將包含相應的按鍵lower_bound兩個呼叫。例如

auto first1 = m1.lower_bound(minmax1.first); 
auto last1 = m1.lower_bound(minmax1.second); 

如果你想排除的範圍的下限,那麼你可以寫

auto first1 = m1.upper_bound(minmax1.first); 
auto last1 = m1.upper_bound(minmax1.second); 
1

使用std::map::lower_bound

// All elements in [KEY1 KEY2) 
auto it1 = m.lower_bound (KEY_1 ) ; 
auto it2 = m.lower_bound( KEY_2 ) ; 

for(auto it = it1 ; it != it2 ; ++it) 
{ 
    // it->first , it->second 
} 
+0

演示[_Here_](http://rextester.com/WSHH37077) – P0W 2014-11-01 09:33:29

+0

演示正確使用'lower_bound'兩次。你應該在你的回答中做同樣的事情。 :) – hvd 2014-11-01 09:40:33

+0

@ hvd是的,我忘了更新,謝謝 – P0W 2014-11-01 09:43:15

相關問題