1

I have a c++ map where the value type is a bool. I need to see if a key exists in the map, and if it doesn't, return false. This is my code right now:

try {
  return board.at[{x, y}];
}
catch (const std::out_of_range& oor) {
  return false;
}

I don't want to use the [] operator because that will initialize the value if it doesn't exist. Is there any way to see if the value exists in the map without a try block?

Simon Shkolnik
  • 368
  • 3
  • 12

2 Answers2

2

You can use std::map::find which will return an iterator the element if found, or .end if not found.

return board.find({x, y}) != board.end();
Cory Kramer
  • 114,268
  • 16
  • 167
  • 218
1

return my_map.count({x, y}) is the idiomatic way, and has the advantage of the implicit bool conversion.

C++20 adds bool contains( const Key& key ) const.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483