2015-04-06 55 views
2

我有一個查找問題的代碼,並不確定正確的解釋迭代器測試。問題是這樣的:我有一個set並使用upper_bound進行查找,然後想要查找下一個最低元素。像這樣:C++ std :: set upper_bound迭代器行爲

#include <iostream> 
#include <set> 
#include <algorithm> 

void exploreSet(std::set<int> &int_set, int key); 

int main() 
{ 
    std::set<int> int_set { 5, 10, 12, 17, 19 }; 
    exploreSet(int_set, 15); 
    exploreSet(int_set, 4); 
    return 0; 
} 


void exploreSet(std::set<int> &int_set, int key) 
{ 
    auto it = int_set.upper_bound(key); 
    if (it==int_set.end()) 
    { 
     std::cout << "Nothing found.\n"; 
    } 
    else 
    { 
     std::cout << "Found " << *it << ".\n"; 
     // Now find the next lowest value -- how? 
     auto it_back = it; 
     --it_back; 
     if (it_back==int_set.end()) 
     { 
      std::cout << "Nothing prior.\n"; 
     } 
     else 
     { 
      std::cout << "Prior value: " << *it_back << ".\n"; 
     } 
    } 
} 

所得上的gcc 4.9.2與STD運行此= C++ 14的輸出:

Found 17. 
Prior value: 12. 
Found 5. 
Nothing prior. 

這工作。但爲什麼?

當通過upper_bound獲得的迭代器向後進行比較時,與std :: set :: end()進行比較是否正確?爲什麼或者爲什麼不?

+0

// Now find the next lowest value -- how? if (it == int_set.begin()) { std::cout << "Nothing prior.\n"; } else { auto it_back = it; --it_back; std::cout << "Prior value: " << *it_back << ".\n"; } 

這麼說,我反而會建議使用std::set<int, std::greater<int>>lower_bound一起lower_bound'?在一個'set'上它直接到你想要的。 –

+0

@MooingDuck只有當你使用'std :: greater'作爲集合的比較器 –

+0

@AntonSavin:我對你的評論感到非常困惑。他的算法似乎顯示的最大值小於或等於'std :: less'命令的容器中的給定鍵,這正是'lower_bound'在默認情況下所做的。我誤解了什麼? –

回答

2

不,這是不正確的。減量迭代器等於begin()是未定義的行爲。參見[bidirectional.iterators]/1,表110:

表達
--r
斷言/音符前置/後置條件
預:存在s使得r == ++s
post:r是可解引用的。

所以正確的方法是比較itint_set.begin():你爲什麼不能簡單地使用`

template <typename Set> 
void exploreSet(const Set& int_set, int key) { 
    auto it = int_set.lower_bound(key); 
    if (it == int_set.end()) 
     std::cout << "Nothing found.\n"; 
    else 
     std::cout << "Found " << *it << ".\n"; 
} 

int main() { 
    std::set<int, std::greater<int>> int_set { 5, 10, 12, 17, 19 }; 
    exploreSet(int_set, 15); 
    exploreSet(int_set, 4); 
} 
+0

謝謝。這回答了這個問題。 –

相關問題