I have a map of the form map<key1, map<key2, value> > :
For Example: I am storing the intensity value at 2-D co-ordinate(x,y) in following map:
map<int, map<int, double> > intensityValue;
Now, I want to check whether intensity value at co-ordinate (x,y) exist in this map or not. One way that I know is to check :
if(intensityvalue[x][y] >=0)
in this case, if intensityValue[x][y] does not exist in map then after checking it will automatically insert intensityValue[x][y] in the map which I don't want.
Please suggest an efficient way, so that I can check whether intensityValue[x][y] already exist in the map or not without inserting it in the map.
You can use std::map::find together with short-circuit evaluation:
bool foundXY = instensityValue.find(x) != intensityValue.end() &&
intensityValue[x].find(y) != intensityValue[x].end();
or std::map::count:
bool foundXY = instensityValue.count(x) && intensityValue[x].count(y)
You can use std::map::find and check if the element exists before accessing it. You can read the usage/documentation here: http://en.cppreference.com/w/cpp/container/map/find
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With