Hi,
Say if, like in the following example, you want to check if a variable has one of two sets of values. Is there a way of doing this, but without writing out "a1 = 12, a2 = ...." etc.?
I'm thinking you could do it with two arrays- one for the first set of values then another for the second set. Then you would just assign one of those arrays to a vector and check if c is any of the values in the vector. But I'm wondering, would it be possible to do this with using only 1 array or vector? Something like:
Or is there any other more efficient way to do the program?Code:vector<int> v1; if (b == 1) v1 = {12, 15, 11, 17, 18 }; if (b == 2) v1 = {21, 25, 27, 26, 28 };
Thanks.
Code:#include <iostream> using namespace std; int main() { int a1, a2, a3, a4, a5, b, c; cout << "press 1 for set 1 and 2 for set 2"; cin >> b; if (b == 1) { a1 = 12; a2 = 15; a3 = 11; a4 = 17; a5 = 18; } else if (b == 2) { a1 = 21; a2 = 25; a3 = 27; a4 = 26; a5 = 28; } cout << "Enter a number to check if it's in the set selected"; cin >> c; if (c == a1 || c == a2 || c == a3 || c == a4 || c == a5) cout << "You entered a value that is in set " << b; else cout << "Number not in set " << b; }



LinkBack URL
About LinkBacks


