How can I get a range of values ​​in a map for a given lower bound and upper bound in std :: set?

Say I have the following code

#include <iostream>
#include <set>

int main ()
{
  std::set<int> myset;
  int inf, sup;

  inf = 25; sup = 60;
  for (int i=1; i<10; i++) myset.insert(i*10); // 10 20 30 40 50 60 70 80 90

  return 0;
}

I was trying to find out if the standard library provides any methods or a combination of methods that would allow me to get two iterators it_l, it_uto cover the range [inf, sup]. I tried using lower_bound, upper_bound, but I misunderstood how they work. The idea would be to not write loops (because I know that I can write my own function for this task, but maybe there is an alternative that I don't know about).

Update: some examples of expected output will be (in my example)

inf =25; sup = 60 I expect {30,40,50,60}

if instead

inf=30; sup = 60 I expect {30,40,50,60}

if

inf=25; sup = 65 I expect {30,40,50,60}

-, , , , , .

inf sup, . , , [inf, sup] , . - , , ?

A={10 20 30 40 50 60 70 80 90}, B1=[25,60], B2=[30,60] B3=[25,65]

i=1,2,3 A Bi , .

+4
4

:

#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;

  for (int i=1; i<10; i++) myset.insert(i*10); // 10 20 30 40 50 60 70 80 90

  for (auto its = infsup(myset, 30, 60); its.first != its.second; ++its.first)
  {
    std::cout << " " << *its.first; // 30 40 50 60
  }
  std::cout << std::endl;

  for (auto its = infsup(myset, 25, 65); its.first != its.second; ++its.first)
  {
    std::cout << " " << *its.first; // 30 40 50 60
  }
  std::cout << std::endl;

  return 0;
}

lower_bound inf , , inf, , .

upper_bound sup , , , sup _, , ++ , sup .

, ( @Useless ): , , .

  • inf sup
  • ,
  • [inf, sup] ( , inf=25, sup=29)

inf > sup, , its.first > its.second, for ( ), . , inf <= sup ( for, ).

+4

, :

auto it_l = myset.lower_bound(inf);
auto it_u = myset.lower_bound(sup + 1);

, [it_l, it_u), i myset inf <= i <= sup ( , ). - , , .

+1

++ . [inf, sup), [inf, sup]. : std::set::lower_bound std::set::upper_bound. ( std::upper bound ..). , , . .

0

, , , .

lower_bound , , ( , )

upper_bound gives you the first element other than the argument (e.g. 70 in your example), but the way the stl iterators work ends with one element after the last element.

These 2 iterators can be used to create a copy of the elements if you really want a copy, but you can also just use them to access the elements of the original collection, and this range will include 60, but not 70 in your example.

0
source

Source: https://habr.com/ru/post/1660171/


All Articles