Determining if a number is either a multiple of ten or within a particular set of ranges

后端 未结 13 1583
Happy的楠姐
Happy的楠姐 2021-01-31 07:01

I have a few loops that I need in my program. I can write out the pseudo code, but I\'m not entirely sure how to write them logically.

I need -

if (num is          


        
13条回答
  •  谎友^
    谎友^ (楼主)
    2021-01-31 07:21

    This is for future visitors more so than a beginner. For a more general, algorithm-like solution, you can take a list of starting and ending values and check if a passed value is within one of them:

    template
    bool in_any_interval(It first, It last, const Elem &val) {
        return std::any_of(first, last, [&val](const auto &p) {
            return p.first <= val && val <= p.second;
        });
    }
    

    For simplicity, I used a polymorphic lambda (C++14) instead of an explicit pair argument. This should also probably stick to using < and == to be consistent with the standard algorithms, but it works like this as long as Elem has <= defined for it. Anyway, it can be used like this:

    std::pair intervals[]{
        {11, 20}, {31, 40}, {51, 60}, {71, 80}, {91, 100}
    };
    
    const int num = 15;
    std::cout << in_any_interval(std::begin(intervals), std::end(intervals), num);
    

    There's a live example here.

提交回复
热议问题