我有一個查找問題的代碼,並不確定正確的解釋迭代器測試。問題是這樣的:我有一個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()進行比較是否正確?爲什麼或者爲什麼不?
:
這麼說,我反而會建議使用
std::set<int, std::greater<int>>
與lower_bound
一起lower_bound'?在一個'set'上它直接到你想要的。 –@MooingDuck只有當你使用'std :: greater'作爲集合的比較器 –
@AntonSavin:我對你的評論感到非常困惑。他的算法似乎顯示的最大值小於或等於'std :: less'命令的容器中的給定鍵,這正是'lower_bound'在默認情況下所做的。我誤解了什麼? –