I had a lookup problem to code and was unsure about correct interpretation of iterator testing. The problem is this: I have a set and do a lookup using upper_bound, then want to find the next lowest element. Like this:
#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";
}
}
}
Resulting output of running this on gcc 4.9.2 with std=c++14:
Found 17.
Prior value: 12.
Found 5.
Nothing prior.
This works. But why?
Is it correct to compare against std::set::end() when going backwards on an iterator obtained through upper_bound? Why or why not?
Aucun commentaire:
Enregistrer un commentaire