c++ - How Can I get a range of values in a map for given lower bound and upper bound in an std::set? -
say have following code
#include <iostream> #include <set> int main () { std::set<int> myset; int inf, sup; inf = 25; sup = 60; (int i=1; i<10; i++) myset.insert(i*10); // 10 20 30 40 50 60 70 80 90 return 0; }
i trying figure out if standard library provides methods, or combination of methods allow me 2 iterators it_l, it_u
such range [inf,sup] covered. i've tried use lower_bound, upper_bound i've misunderstood how works. idea avoiding write loops (because know write own function task, maybe there's alternative i'm not aware of).
update : examples of expected output (in example)
inf =25; sup = 60
expect {30,40,50,60}
if instead
inf=30; sup = 60
expect {30,40,50,60}
if
inf=25; sup = 65
expect {30,40,50,60}
apparently there's misunderstanding, or maybe it's me i'm not correctly expressing want do.
when inf , sup please intend them extreme values of real interval. once made such assumption want retrieve intersection between interval [inf,sup] , discrete set specified set objects. there contradiction between said , examples?
let a={10 20 30 40 50 60 70 80 90}
,b1=[25,60]
,b2=[30,60]
, b3=[25,65]
for each i=1,2,3
intersection between a
, bi
gives i've said in examples.
this works fine me:
#include <iostream> #include <set> template <typename t> std::pair<typename std::set<t>::const_iterator, typename std::set<t>::const_iterator> infsup(const std::set<t>& set, const t& inf, const t& sup) { return std::make_pair(set.lower_bound(inf), set.upper_bound(sup)); } int main () { std::set<int> myset; int inf, sup; (int i=1; i<10; i++) myset.insert(i*10); // 10 20 30 40 50 60 70 80 90 (auto = infsup(myset, 30, 60); its.first != its.second; ++its.first) { std::cout << " " << *its.first; // 30 40 50 60 } std::cout << std::endl; (auto = infsup(myset, 25, 65); its.first != its.second; ++its.first) { std::cout << " " << *its.first; // 30 40 50 60 } std::cout << std::endl; return 0; }
using lower_bound
inf
means start iterator point the first element not less inf
, , fulfills condition want lower end of range.
using upper_bound
sup
means end iterator point _ first element greater sup
_. note end iterator, in c++, points just past end of range, therefore sup
included.
edit reflect discussion in comments (thanks @useless pointing out): note works fine empty result ranges, e.g.
- when both
inf
,sup
less smallest element in set - when both greater greatest element
- when there no elements within [inf, sup] (in example,
inf=25, sup=29
)
but if pick inf > sup
returned iterators refer different elements, its.first > its.second
, make for
loops (as wrote them above) fail. ensure inf <= sup
(just other for
loop might writing).
Comments
Post a Comment