c++ - std::set, how do lower_bound and upper_bound work? -


i have simple piece of code:

#include <iostream> #include <set>  using std::set;  int main(int argc, char argv) {    set<int> myset;    set<int>::iterator it_l, it_u;    myset.insert(10);    it_l = myset.lower_bound(11);    it_u = myset.upper_bound(9);     std::cout << *it_l << " " << *it_u << std::endl; } 

this prints 1 lower bound 11, , 10 upper bound 9.

i don't understand why 1 printed. hoping use these 2 methods range of values given upper bound / lower bound.

from cppreference.com on std::set::lower_bound:

return value

iterator pointing first element not less key. if no such element found, past-the-end iterator (see end()) returned.

in case, since have no elements in set not less (i.e. greater or equal) 11, past-the-end iterator returned , assigned it_l. in line:

std::cout << *it_l << " " << *it_u << std::endl; 

you're deferencing past-the-end iterator it_l: that's undefined behavior, , can result in (1 in test, 0 or other value other compiler, or program may crash).

your lower bound should less than, or equal to upper bound, , should not dereference iterators outside loop or other tested environment:

#include <iostream> #include <set>  using std::set;  int main(int argc, char argv) {    set<int> myset;    set<int>::iterator it_l, it_u;    myset.insert(9);    myset.insert(10);    myset.insert(11);    it_l = myset.lower_bound(10);    it_u = myset.upper_bound(10);      while(it_l != it_u)     {         std::cout << *it_l << std::endl; // print 10         it_l++;     } } 

Comments

Popular posts from this blog

php - How to add and update images or image url in Volusion using Volusion API -

javascript - IE9 error '$'is not defined -