Can I make enumerations of variables in if statemants?

Viewed 66

I am trying to learn C++ (Beginner). But I wonder how I can make an enumeration of variables in statements like if.

Do I just put a comma between variables? What is the right syntax for this.. or is this all good?

#include <iostream>
using namespace std;

int main()
{
   int a, b, c, d, e;
   cin >> a >> b >> c >> d >> e;
   if (a, b, c > e && a, b, c > d) 
   {
      cout << a + b + c;
   }
}
3 Answers

No, there is nothing in C++ like that. You'll need to split each of those into their own statement, like:

if (a > e && b > e && c > e && a > d && b > d && c > d){

However, the logic here can be simplified.

If you want a > e AND a > d, then you only need to show that a is greater than the larger of e and d. The reverse is true for a, b and c. In other words, you only need to check that the smallest of a/b/c is greater than the largest of e/d.

So this can become:

if (min({a, b, c}) > max(e, d)){

You can not do what you have tried there in the code.

The obvious way (beginner)way has been shown in the @scohe001's answer. However, when you learn at some point the templates and fold expressions, the following solution would be much compact and similar to what you have tried to do.

#include <iostream>
#include <utility>

template<typename... Args>
constexpr bool all_of_greater(const int lhs, Args&&... rhsArgs)
{
   return ((lhs < std::forward<Args>(rhsArgs)) && ...);
}

Now you could do similar to what you have done in the code:

if (all_of_greater(e, a, b, c) && all_of_greater(d, a, b, c))
{
   std::cout << a + b + c;
}

(See Online Demo)

Here's a reworked approach where the "values" and the "targets" are split into two separate vector structures to ease comparison:

#include <algorithm>
#include <iostream>
#include <numeric>
#include <vector>

// Helper function to read an arbitrary number of entries into a vector
void read_n(std::vector<int>& list, const size_t n) {
  for (size_t i = 0; i < n; ++i) {
    int v;
    std::cin >> v;
    list.push_back(v);
  }
}

int main() {
  // Container to hold the values
  std::vector<int> values;

  read_n(values, 3);

  // Container to hold the targets
  std::vector<int> targets;

  read_n(targets, 2);

  // Ensure that for each target...
  for (auto target : targets) {
    // ...all of the values exceed that target...
    if (!std::all_of(values.cbegin(), values.cend(), [target](int i) { return i > target; })) {
      // ...or else it's a fail.
      return -1;
    }
  }

  // Use accumulate to compute the sum and display it.
  std::cout << std::accumulate(values.cbegin(), values.cend(), 0) << std::endl;

  return 0;
}

When writing code try and think in terms of structure and loops rather than just copy-pasting code to add more variables.

Related