I have a map which I have declared as follows:
map<int, bool> index;
and I insert values into the map as:
int x; cin>>x;
index[x]=true;
However,
cout<<index[y]; // for any number y not inindexgives me 0
- As I get the value
0when I check for a key which is not present in the map, how can I reliably find out if a key is present in the map or not? - I’m using a map for trying to find out if two sets are disjoint or not, and for the same I am using a map, and two vectors to store the input. Is this shabby in any way? Some other data structure I should be using?
You can use
if (index.find(key) == index.end())to determine if a key is present. Usingindex[key]you default-construct a new value (in this case, you callbool(), and it gets printed as0.) The newly constructed value also gets inserted into the map (i.e.index[key]is equal in this case toindex.insert(std::make_pair(key, bool()).)Using two data structures for the same data is ok. However, is there any need to use a map, wouldn’t a set suffice in your use case? I.e. if they key is presents, the value is true, and false otherwise?