Ghostff
Ghostff

Reputation: 1458

c++ If all condition are met

Is there any way to check if all conditions are met? e.g:

if(num[i] > (*all*)alt[c])
{
}

Instead of doing it this way

if(num[i] > alt[1] && num[i] > alt[2] && num[i] > alt[3])
{
}

Like is there a shorter way?

Upvotes: 2

Views: 449

Answers (3)

AnArrayOfFunctions
AnArrayOfFunctions

Reputation: 3744

For now no, at least without creating additional code (instead of evaluating at compile-time). But if you use 'inline' variables (currently only an early draft - idea of mine), you could write:

auto FuncCheckingMulCond(auto &inline varSrc, auto &inline varTarget, inline size_t nTimes)
{
    for(inline size_t i(0); i < nTimes; ++i)
        if(!(varSrc > varTarget[i]))
            return false;

    return true;
}

And so your example will look like this:

if(FuncCheckingMulCond(num[i], alt, 5))
{
}

Inline variables should be such which value is known at compile-time and as 'FuncCheckingMulCond' contain 'inline' parameters it should be evaluated at compile-time too. '&inline' is an inline reference which means that it instead of storing some pointer, all it's instances are replaced with the variable it had bound to. So in theory - the above code should do exactly the thing you wanted, but unfortunately this isn't part of ISO C++ yet.

Upvotes: 0

zmbq
zmbq

Reputation: 39013

Well, you can take the maximum of all alts, and then compare num[i] to it.

Get the maximum element with:

auto max = std::max_element(alt.begin(), alt.end());

Upvotes: 7

Dietmar K&#252;hl
Dietmar K&#252;hl

Reputation: 153792

You could use a suitable auxiliary function which effectively just calls one of the algorithms, e.g.:

 if (is_bigger(num[i], alts)) {
     // ...
 }

where the function is_bigger() just uses std::all_of() with a suitable condition:

template <typename T, typename Sequence>
bool is_bigger(T const& test, Sequence const& alts) {
    return std::all_of(alts.begin(), alts.end(),
         [&](T const& other){ return test > other; });
}

all_of() is simple an algorithm which applies a predicate to all elements in the sequence delimited by the begin and end iterator (alts.begin() and alts.end()). The other thing in this function is simple a lambda expression creating a corresponding predicate.

Upvotes: 9

Related Questions