2

What is the right way to implement the function below to allow the caller to iterate over the range it returns?

#include <set>
#include <ranges>

std::set<int> set{1, 2, 3, 4, 5, 6, 7, 8, 9, 10};

auto find_range(int a)
{
    //What type should I return?
    return std::make_tuple(set.lower_bound(a - 3), set.upper_bound(a + 3));
}

int main()
{
    for (int x : find_range(5)) {...}
}

The function returns a couple of iterators pointing to 2 and 9, so the loop should iterate over 2, 3, 4, 5, 6, 7, 8.

4
  • I'm not sure what you're trying to return from the function. Could you show an example value of set and the desired output? Commented Sep 8, 2021 at 0:07
  • 1
    @cigien updated the post Commented Sep 8, 2021 at 0:11
  • 1
    Are you looking to return a container or a view? Containers carry the data while views are based on some other source of data (which could be, e.g., a container or instructions for how to generate the sequence). Commented Sep 8, 2021 at 0:13
  • @chris I need a view. Commented Sep 8, 2021 at 0:13

1 Answer 1

3

You can return a subrange like this

auto find_range(int a)
{
    return std::ranges::subrange(set.lower_bound(a - 3), 
                                 set.upper_bound(a + 3));
}

Here's a demo.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.