How to quickly compare an integer to multiple integers?

I'm working on a simple text game, but with their being several items usable by a single class, I want to make sure that a variable called equippeditemID can be compared quickly to the item ID's of other items. I know I could use several if statements to complete this, but is there any easier way?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
#include <iostream>
#include <vector>
#include <initializer_list>

int main()
{
    {
        // if the ids of items are already in a sequence, say a vector

        std::vector<int> ids_in_use = { 7, 8, 5, 22, 17 } ;

        int candidate_id = 5 ;

        bool unique = true ;
        for( int existing_id : ids_in_use )
           if( candidate_id == existing_id ) { unique = false ; break ; }

        // check if unique is true
        // ...
    }

    {
        // if the ids of items are already in a sequence, say an array:

        int ids_in_use[100] = { 7, 8, 5, 22, 17 } ;
        int cnt_ids_in_use = 5 ;

        int candidate_id = 5 ;

        bool unique = true ;
        for( int i = 0 ; i < cnt_ids_in_use ; ++i )
           if( candidate_id == ids_in_use[i] ) { unique = false ; break ; }

        // check if unique is true
        // ...
    }

    {
        // if not (probably not a good idea if there are many ids)

        int id1 = 7, id2 = 8, id3 = 5, id4 = 22, id5 = 17 ;

        int candidate_id = 5 ;

        bool unique = true ;
        for( int existing_id : { id1, id2, id3, id4, id5 } )
           if( candidate_id == existing_id ) { unique = false ; break ; }

        // check if unique is true
        // ...
    }
}
there are other ways. If the arrays were sorted, as soon as you found a value > than what you were looking for, you can stop looking. That cuts your average loop time in half, and at the worst case, same as above.

more exciting, if you are looking for uniqueness, you can do this..

vector<bool> inuse; //set this to all false and reserve enough for 0 to your highest item ID number.

...player gets an item in game:
if (inuse[item.id]) unique = false;

inuse[item.id] = true;

you don't even have to loop, at the expense of a little memory and the trouble of setting this up everywhere.


This works great for the uniqueness problem. The question is, do you have other cross comparisons going on...
Last edited on
Topic archived. No new replies allowed.