Help with Arrays

Hello,

i wanted to ask something. For example i have an Array called bool Marked[10] from 0-9 and i want to use something like this

 
  if(!Marked[0] && Marked[1] && Marked[2] && Marked[3]) //until 9 


Is there a Way to make it shorter for 0-9 or 0-5 etc. ?
no.
you can use an integer, though. a 32 bit integer is like 32 Booleans. you could also look at bitset, which I haven't studied deeply.

consider
...0000000001111111110 as an integer is 1022.
so you can say if marked == 1022 and its done. //this would require a GOOD comment and a good name for the magic number!!!

setting a bit is as simple as marked | a power of 2 (including 2 to the zero, first bit, 2 to the 1, second bit, 2 to the 2, third bit, … etc). Clearing a bit can be done with and or xor.

I would look at the bitset, though. Its probably going to be doing the same thing with a better interface.
Last edited on
I won't admit this is the best solution out there but with some quick testing I have come up with a solution but it can depend on the context of your program how useful it will be.

The way I have done it is to use a for loop to check through all of the items in the array that you wish to check. Altering the num_start variable and the num_end variable you can determine what range you wish to check. These numbers are the index numbers you wish to check. So to check from 1 through 9, num_start is 1 and num_end is 9. if you wanted to check 1 through 5 then num_end can be changed to 5, etc. Again, this is not a perfect solution but this works.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
    // check all the values if they're all true
    int num_start = 1; // <-- number to start check from
    int num_end = 9; // <-- number to check up to
    bool pass = true;
    for (unsigned int i = num_start; i < num_end + 1; i++) {
        // check if the current value is false
        if (!Marked[i]) {
            // the current value is false, so no need to check the other values for && operand
            pass = false;
            break;
        }
    }

    // THEN
    if (!Marked[0] && pass) {
        // do whatever
        cout << "Success!" << endl;
    } else {
        // the conditions have not been met
        cout << "Failure!" << endl;
    }
Last edited on
Depending on quite what logic you are implementing you could use one of the algorithms
std::all_of
std::any_of
std::none_of
or even
std::find
etc.
See http://www.cplusplus.com/reference/algorithm/

Did you intend in your example for !Marked[0], whilst all the others are without the ! ?
Last edited on
Topic archived. No new replies allowed.